SlideShare una empresa de Scribd logo
1 de 65
Descargar para leer sin conexión
Scala
2018/11/10 Scala Summit 2018
• @itohiro73
• FOLIO
• Reladomo in Scala Scala
Summit 2017
• 2009 Satoshi Nakamoto
Bitcoin https://bitcoin.org/bitcoin.pdf
• Bitcoin
•
• 2017
•
•
•
🙋
👍
0
🤔
•
✓
• Proof of Work
✓
✓nonse Proof of Work
✓mining
•
•
•
•
import java.math.BigInteger
import java.security.MessageDigest
object HashFunction {
val MD_SHA256 = MessageDigest.getInstance("SHA-256")
def sha256(input: String): String =
{
String.format("%064x", new BigInteger(1,
MD_SHA256.digest(input.getBytes("UTF-8"))))
}
}
scala> HashFunction.sha256("a")
res0: String =
ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785
afee48bb
scala> HashFunction.sha256("test")
res1: String =
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15
b0f00a08
scala> HashFunction.sha256("same input")
res2: String =
c2f991739d5824b4e1d8bafaffb735b9e4061f801d82c4aaf57aea02
495f750c
scala> HashFunction.sha256("same input")
res3: String =
c2f991739d5824b4e1d8bafaffb735b9e4061f801d82c4aaf57aea02
495f750c
??? =
f0157537806d0ec6fd86455f6603bbaf1efed378798bcb43377456bc
6a8bfd78
scala> HashFunction.sha256("random input1")
res5: String =
3ef129a908f6b5e0c11cade17bb27691f6bd8cfffbb18622448a5fb229ca724d
scala> HashFunction.sha256("random input2")
res6: String =
dac708dccfe5ccbf009c9e5cd43ee9bf592abd0c7c04b421d8fe79f7518784c3
scala> HashFunction.sha256("random input3")
res7: String =
30b9b0875d568d926cf653f2360e95c86e8b798574a0ec95ceb7ef43cc9768ad
class Block(val timestamp: LocalDateTime, val data:
String, val previousHash: String) {
val hash = calculateHash()
def calculateHash(): String = {
val value = timestamp.toString + data + previousHash
HashFunction.sha256(value)
}
}
override def toString: String = {
"{ntTimestamp: " + this.timestamp +
"ntData: " + this.data +
"ntPrevious Hash: " + this.previousHash +
"ntHash:" + this.hash +
"n}"
}
class Blockchain(){
var chain = Seq[Block](createGenesisBlock())
def createGenesisBlock(): Block = {
new Block(LocalDateTime.now(), "A genesis block")
}
def addBlock(block: Block): Unit = {
this.chain = this.chain :+ block
}
def getLastBlock(): Block = {
this.chain.last
}
}
override def toString: String = {
this.chain.mkString("n")
}
def isChainValid(): Boolean = {
for(i <- 1 until this.chain.length) {
val currentBlock = this.chain(i)
val previousBlock = this.chain(i-1)
if(currentBlock.hash != currentBlock.calculateHash())
return false
if(currentBlock.previousHash != previousBlock.hash)
return false
}
return true
}
•Bitcoin Proof of
Work
•Proof of Work
0
✓ Satoshi Nakamoto
•
• nonce
• mining
• =difficulty
✓Bitcoin 10 difficulty
• nonce
• nonce
class Block(val timestamp: LocalDateTime, val data: String, val previousHash: String = "") {
var hash = calculateHash()
var nonce = 0
def calculateHash(): String = {
val value = timestamp.toString + data + previousHash + nonce
HashFunction.sha256(value)
}
def mineBlock(difficulty: Int): Unit = {
while(this.hash.substring(0, difficulty) != Array.fill(difficulty)("0").mkString ) {
this.nonce += 1
this.hash = calculateHash()
}
println("Block mined: " + this.hash)
}
class Blockchain {
var chain = Seq[Block](createGenesisBlock())
val difficulty = 4
def createGenesisBlock(): Block = {
new Block(LocalDateTime.now(), "A genesis block.")
}
def addBlock(block: Block): Unit = {
block.mineBlock(difficulty)
this.chain = this.chain :+ block
}
•nonce
Proof of Work
•Blockchain Block
class Transaction(val fromAddress: String, val
toAddress: String, val amount: Double) {
override def toString: String = {
"From Address: " + fromAddress + ", To Address: " +
toAddress + ", Amount: " + amount
}
}
import java.time.LocalDateTime
class Block(val timestamp: LocalDateTime, val transactions: Seq[Transaction], val previousHash: String = "") {
var hash = this.calculateHash()
var nonce = 0
def calculateHash(): String = {
val value = this.timestamp + this.transactions.mkString + this.previousHash + this.nonce
HashFunction.sha256(value)
}
def mineBlock(difficulty: Int): Unit = {
while(this.hash.substring(0, difficulty) != Array.fill(difficulty)("0").mkString) {
this.nonce += 1
this.hash = this.calculateHash()
}
}
override def toString: String = {
"{ntTimestamp: " + this.timestamp +
"ntTransaction: " + this.transactions.mkString("ntt{nttt", "nttt", "ntt}") +
"ntPrevious Hash: " + this.previousHash +
"ntHash: " + this.hash +
"ntNonse: " + this.nonce +
"n}"
}
class Blockchain {
var chain = Seq[Block](createGenesisBlock())
val difficulty = 4
var pendingTransactions = Seq[Transaction]()
val miningReward = 100
def createGenesisBlock(): Block = {
new Block(LocalDateTime.now(), Seq(new
Transaction("", "Initial Pool Address", 500)))
}
def addTransaction(transaction: Transaction): Unit = {
this.pendingTransactions = this.pendingTransactions :+ transaction
}
def minePendingTransactions(rewardAddress: String): Unit = {
val newBlock = new Block(LocalDateTime.now(), this.pendingTransactions)
newBlock.mineBlock(this.difficulty)
println("Block successfully mined: " + newBlock)
this.chain = this.chain :+ newBlock
this.pendingTransactions = Seq[Transaction](new Transaction("Reward",
rewardAddress, this.miningReward))
}
def getBalanceOfAddress(address: String): Double = {
var balance = 0.0
this.chain.flatMap(block =>
block.transactions).foreach(transaction => {
if(transaction.fromAddress == address)
balance -= transaction.amount
if(transaction.toAddress == address)
balance += transaction.amount
})
balance
}
•
✓
• Proof of Work
✓
✓nonse Proof of Work
✓mining
https://github.com/itohiro73/blockchain-scala
Satoshi Nakamoto (2009) Bitcoin: A Peer-to-Peer Electronic Cash System
2017
2018
Building a blockchain with Javascript

Más contenido relacionado

La actualidad más candente

Scala の関数型プログラミングを支える技術
Scala の関数型プログラミングを支える技術Scala の関数型プログラミングを支える技術
Scala の関数型プログラミングを支える技術Naoki Aoyama
 
CMSでのXSS to RCEを触ってみた
CMSでのXSS to RCEを触ってみたCMSでのXSS to RCEを触ってみた
CMSでのXSS to RCEを触ってみたadachi tomohiro
 
ICML2018読み会: Overview of NLP / Adversarial Attacks
ICML2018読み会: Overview of NLP / Adversarial AttacksICML2018読み会: Overview of NLP / Adversarial Attacks
ICML2018読み会: Overview of NLP / Adversarial AttacksMotoki Sato
 
トランザクションをSerializableにする4つの方法
トランザクションをSerializableにする4つの方法トランザクションをSerializableにする4つの方法
トランザクションをSerializableにする4つの方法Kumazaki Hiroki
 
リーンなコードを書こう:実践的なオブジェクト指向設計
リーンなコードを書こう:実践的なオブジェクト指向設計リーンなコードを書こう:実践的なオブジェクト指向設計
リーンなコードを書こう:実践的なオブジェクト指向設計増田 亨
 
文字コードに起因する脆弱性とその対策(増補版)
文字コードに起因する脆弱性とその対策(増補版)文字コードに起因する脆弱性とその対策(増補版)
文字コードに起因する脆弱性とその対策(増補版)Hiroshi Tokumaru
 
C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)Takuya Kawabe
 
強いて言えば「集約どう実装するのかな、を考える」な話
強いて言えば「集約どう実装するのかな、を考える」な話強いて言えば「集約どう実装するのかな、を考える」な話
強いて言えば「集約どう実装するのかな、を考える」な話Yoshitaka Kawashima
 
マイクロアドにおけるCTR予測への取り組み
マイクロアドにおけるCTR予測への取り組みマイクロアドにおけるCTR予測への取り組み
マイクロアドにおけるCTR予測への取り組みMicroAd, Inc.(Engineer)
 
Apache Avro vs Protocol Buffers
Apache Avro vs Protocol BuffersApache Avro vs Protocol Buffers
Apache Avro vs Protocol BuffersSeiya Mizuno
 
開発速度が速い #とは(LayerX社内資料)
開発速度が速い #とは(LayerX社内資料)開発速度が速い #とは(LayerX社内資料)
開発速度が速い #とは(LayerX社内資料)mosa siru
 
MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...
MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...
MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...NTT DATA Technology & Innovation
 
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)NTT DATA Technology & Innovation
 
AWS + MLflow + SageMakerの環境を動かしてみたお話
AWS + MLflow + SageMakerの環境を動かしてみたお話AWS + MLflow + SageMakerの環境を動かしてみたお話
AWS + MLflow + SageMakerの環境を動かしてみたお話ItohHiroki
 
研究について思うところ | What i think about research (in Japanese)
研究について思うところ | What i think about research (in Japanese)研究について思うところ | What i think about research (in Japanese)
研究について思うところ | What i think about research (in Japanese)Yuta Itoh
 
DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡
DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡
DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡BIGLOBE Inc.
 
ChordアルゴリズムによるDHT入門
ChordアルゴリズムによるDHT入門ChordアルゴリズムによるDHT入門
ChordアルゴリズムによるDHT入門Hiroya Nagao
 
言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-
言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-
言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-Takahiro Kubo
 

La actualidad más candente (20)

Scala の関数型プログラミングを支える技術
Scala の関数型プログラミングを支える技術Scala の関数型プログラミングを支える技術
Scala の関数型プログラミングを支える技術
 
CMSでのXSS to RCEを触ってみた
CMSでのXSS to RCEを触ってみたCMSでのXSS to RCEを触ってみた
CMSでのXSS to RCEを触ってみた
 
ICML2018読み会: Overview of NLP / Adversarial Attacks
ICML2018読み会: Overview of NLP / Adversarial AttacksICML2018読み会: Overview of NLP / Adversarial Attacks
ICML2018読み会: Overview of NLP / Adversarial Attacks
 
分散トレーシング技術について(Open tracingやjaeger)
分散トレーシング技術について(Open tracingやjaeger)分散トレーシング技術について(Open tracingやjaeger)
分散トレーシング技術について(Open tracingやjaeger)
 
トランザクションをSerializableにする4つの方法
トランザクションをSerializableにする4つの方法トランザクションをSerializableにする4つの方法
トランザクションをSerializableにする4つの方法
 
リーンなコードを書こう:実践的なオブジェクト指向設計
リーンなコードを書こう:実践的なオブジェクト指向設計リーンなコードを書こう:実践的なオブジェクト指向設計
リーンなコードを書こう:実践的なオブジェクト指向設計
 
文字コードに起因する脆弱性とその対策(増補版)
文字コードに起因する脆弱性とその対策(増補版)文字コードに起因する脆弱性とその対策(増補版)
文字コードに起因する脆弱性とその対策(増補版)
 
C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)
 
強いて言えば「集約どう実装するのかな、を考える」な話
強いて言えば「集約どう実装するのかな、を考える」な話強いて言えば「集約どう実装するのかな、を考える」な話
強いて言えば「集約どう実装するのかな、を考える」な話
 
Consistent hash
Consistent hashConsistent hash
Consistent hash
 
マイクロアドにおけるCTR予測への取り組み
マイクロアドにおけるCTR予測への取り組みマイクロアドにおけるCTR予測への取り組み
マイクロアドにおけるCTR予測への取り組み
 
Apache Avro vs Protocol Buffers
Apache Avro vs Protocol BuffersApache Avro vs Protocol Buffers
Apache Avro vs Protocol Buffers
 
開発速度が速い #とは(LayerX社内資料)
開発速度が速い #とは(LayerX社内資料)開発速度が速い #とは(LayerX社内資料)
開発速度が速い #とは(LayerX社内資料)
 
MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...
MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...
MLOps に基づく AI/ML 実運用最前線 ~画像、動画データにおける MLOps 事例のご紹介~(映像情報メディア学会2021年冬季大会企画セッショ...
 
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
kubernetes初心者がKnative Lambda Runtime触ってみた(Kubernetes Novice Tokyo #13 発表資料)
 
AWS + MLflow + SageMakerの環境を動かしてみたお話
AWS + MLflow + SageMakerの環境を動かしてみたお話AWS + MLflow + SageMakerの環境を動かしてみたお話
AWS + MLflow + SageMakerの環境を動かしてみたお話
 
研究について思うところ | What i think about research (in Japanese)
研究について思うところ | What i think about research (in Japanese)研究について思うところ | What i think about research (in Japanese)
研究について思うところ | What i think about research (in Japanese)
 
DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡
DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡
DDD Alliance レガシーなコードにドメイン駆動設計で立ち向かった5年間の軌跡
 
ChordアルゴリズムによるDHT入門
ChordアルゴリズムによるDHT入門ChordアルゴリズムによるDHT入門
ChordアルゴリズムによるDHT入門
 
言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-
言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-
言葉のもつ広がりを、モデルの学習に活かそう -one-hot to distribution in language modeling-
 

Similar a Scalaで実装してみる簡易ブロックチェーン

The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
 
Importing Data into Neo4j quickly and easily - StackOverflow
Importing Data into Neo4j quickly and easily - StackOverflowImporting Data into Neo4j quickly and easily - StackOverflow
Importing Data into Neo4j quickly and easily - StackOverflowNeo4j
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopSaša Tatar
 
Graph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easilyGraph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easilyMark Needham
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31Mahmoud Samir Fayed
 
Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
GraphConnect Europe 2016 - Importing Data - Mark Needham, Michael Hunger
GraphConnect Europe 2016 - Importing Data - Mark Needham, Michael HungerGraphConnect Europe 2016 - Importing Data - Mark Needham, Michael Hunger
GraphConnect Europe 2016 - Importing Data - Mark Needham, Michael HungerNeo4j
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 28 of 180
The Ring programming language version 1.5.1 book - Part 28 of 180The Ring programming language version 1.5.1 book - Part 28 of 180
The Ring programming language version 1.5.1 book - Part 28 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 49 of 210
The Ring programming language version 1.9 book - Part 49 of 210The Ring programming language version 1.9 book - Part 49 of 210
The Ring programming language version 1.9 book - Part 49 of 210Mahmoud Samir Fayed
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Stephen Chin
 
The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212Mahmoud Samir Fayed
 
はじめてのUnitTest XCTestに触れて
はじめてのUnitTest XCTestに触れてはじめてのUnitTest XCTestに触れて
はじめてのUnitTest XCTestに触れてKenji Tanaka
 
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based ShardingWebinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based ShardingMongoDB
 
Blockchain com JavaScript
Blockchain com JavaScriptBlockchain com JavaScript
Blockchain com JavaScriptBeto Muniz
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by pythonwonyong hwang
 
Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jqueryDanilo Sousa
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 40 of 180
The Ring programming language version 1.5.1 book - Part 40 of 180The Ring programming language version 1.5.1 book - Part 40 of 180
The Ring programming language version 1.5.1 book - Part 40 of 180Mahmoud Samir Fayed
 

Similar a Scalaで実装してみる簡易ブロックチェーン (20)

The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
Importing Data into Neo4j quickly and easily - StackOverflow
Importing Data into Neo4j quickly and easily - StackOverflowImporting Data into Neo4j quickly and easily - StackOverflow
Importing Data into Neo4j quickly and easily - StackOverflow
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Graph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easilyGraph Connect: Importing data quickly and easily
Graph Connect: Importing data quickly and easily
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
GraphConnect Europe 2016 - Importing Data - Mark Needham, Michael Hunger
GraphConnect Europe 2016 - Importing Data - Mark Needham, Michael HungerGraphConnect Europe 2016 - Importing Data - Mark Needham, Michael Hunger
GraphConnect Europe 2016 - Importing Data - Mark Needham, Michael Hunger
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.4.1 book - Part 13 of 31
 
The Ring programming language version 1.5.1 book - Part 28 of 180
The Ring programming language version 1.5.1 book - Part 28 of 180The Ring programming language version 1.5.1 book - Part 28 of 180
The Ring programming language version 1.5.1 book - Part 28 of 180
 
The Ring programming language version 1.9 book - Part 49 of 210
The Ring programming language version 1.9 book - Part 49 of 210The Ring programming language version 1.9 book - Part 49 of 210
The Ring programming language version 1.9 book - Part 49 of 210
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)
 
The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212
 
はじめてのUnitTest XCTestに触れて
はじめてのUnitTest XCTestに触れてはじめてのUnitTest XCTestに触れて
はじめてのUnitTest XCTestに触れて
 
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based ShardingWebinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
Webinar: MongoDB 2.4 Feature Demo and Q&A on Hash-based Sharding
 
Blockchain com JavaScript
Blockchain com JavaScriptBlockchain com JavaScript
Blockchain com JavaScript
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by python
 
Iniciando com jquery
Iniciando com jqueryIniciando com jquery
Iniciando com jquery
 
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.9 book - Part 53 of 210
 
The Ring programming language version 1.5.1 book - Part 40 of 180
The Ring programming language version 1.5.1 book - Part 40 of 180The Ring programming language version 1.5.1 book - Part 40 of 180
The Ring programming language version 1.5.1 book - Part 40 of 180
 

Último

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 

Último (20)

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 

Scalaで実装してみる簡易ブロックチェーン

  • 2. • @itohiro73 • FOLIO • Reladomo in Scala Scala Summit 2017
  • 3.
  • 4. • 2009 Satoshi Nakamoto Bitcoin https://bitcoin.org/bitcoin.pdf • Bitcoin • • 2017
  • 6.
  • 7.
  • 8.
  • 10.
  • 11.
  • 12. 👍
  • 13.
  • 14. 0
  • 15. 🤔
  • 16.
  • 17.
  • 18. • ✓ • Proof of Work ✓ ✓nonse Proof of Work ✓mining
  • 19.
  • 21. import java.math.BigInteger import java.security.MessageDigest object HashFunction { val MD_SHA256 = MessageDigest.getInstance("SHA-256") def sha256(input: String): String = { String.format("%064x", new BigInteger(1, MD_SHA256.digest(input.getBytes("UTF-8")))) } }
  • 22. scala> HashFunction.sha256("a") res0: String = ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785 afee48bb scala> HashFunction.sha256("test") res1: String = 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15 b0f00a08
  • 23. scala> HashFunction.sha256("same input") res2: String = c2f991739d5824b4e1d8bafaffb735b9e4061f801d82c4aaf57aea02 495f750c scala> HashFunction.sha256("same input") res3: String = c2f991739d5824b4e1d8bafaffb735b9e4061f801d82c4aaf57aea02 495f750c
  • 25. scala> HashFunction.sha256("random input1") res5: String = 3ef129a908f6b5e0c11cade17bb27691f6bd8cfffbb18622448a5fb229ca724d scala> HashFunction.sha256("random input2") res6: String = dac708dccfe5ccbf009c9e5cd43ee9bf592abd0c7c04b421d8fe79f7518784c3 scala> HashFunction.sha256("random input3") res7: String = 30b9b0875d568d926cf653f2360e95c86e8b798574a0ec95ceb7ef43cc9768ad
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31. class Block(val timestamp: LocalDateTime, val data: String, val previousHash: String) { val hash = calculateHash() def calculateHash(): String = { val value = timestamp.toString + data + previousHash HashFunction.sha256(value) } }
  • 32. override def toString: String = { "{ntTimestamp: " + this.timestamp + "ntData: " + this.data + "ntPrevious Hash: " + this.previousHash + "ntHash:" + this.hash + "n}" }
  • 33. class Blockchain(){ var chain = Seq[Block](createGenesisBlock()) def createGenesisBlock(): Block = { new Block(LocalDateTime.now(), "A genesis block") } def addBlock(block: Block): Unit = { this.chain = this.chain :+ block } def getLastBlock(): Block = { this.chain.last } }
  • 34. override def toString: String = { this.chain.mkString("n") }
  • 35. def isChainValid(): Boolean = { for(i <- 1 until this.chain.length) { val currentBlock = this.chain(i) val previousBlock = this.chain(i-1) if(currentBlock.hash != currentBlock.calculateHash()) return false if(currentBlock.previousHash != previousBlock.hash) return false } return true }
  • 36.
  • 37.
  • 38.
  • 39.
  • 40. •Bitcoin Proof of Work •Proof of Work 0 ✓ Satoshi Nakamoto
  • 41. • • nonce • mining • =difficulty ✓Bitcoin 10 difficulty
  • 42.
  • 44. class Block(val timestamp: LocalDateTime, val data: String, val previousHash: String = "") { var hash = calculateHash() var nonce = 0 def calculateHash(): String = { val value = timestamp.toString + data + previousHash + nonce HashFunction.sha256(value) } def mineBlock(difficulty: Int): Unit = { while(this.hash.substring(0, difficulty) != Array.fill(difficulty)("0").mkString ) { this.nonce += 1 this.hash = calculateHash() } println("Block mined: " + this.hash) }
  • 45. class Blockchain { var chain = Seq[Block](createGenesisBlock()) val difficulty = 4 def createGenesisBlock(): Block = { new Block(LocalDateTime.now(), "A genesis block.") } def addBlock(block: Block): Unit = { block.mineBlock(difficulty) this.chain = this.chain :+ block }
  • 46.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56. class Transaction(val fromAddress: String, val toAddress: String, val amount: Double) { override def toString: String = { "From Address: " + fromAddress + ", To Address: " + toAddress + ", Amount: " + amount } }
  • 57. import java.time.LocalDateTime class Block(val timestamp: LocalDateTime, val transactions: Seq[Transaction], val previousHash: String = "") { var hash = this.calculateHash() var nonce = 0 def calculateHash(): String = { val value = this.timestamp + this.transactions.mkString + this.previousHash + this.nonce HashFunction.sha256(value) } def mineBlock(difficulty: Int): Unit = { while(this.hash.substring(0, difficulty) != Array.fill(difficulty)("0").mkString) { this.nonce += 1 this.hash = this.calculateHash() } } override def toString: String = { "{ntTimestamp: " + this.timestamp + "ntTransaction: " + this.transactions.mkString("ntt{nttt", "nttt", "ntt}") + "ntPrevious Hash: " + this.previousHash + "ntHash: " + this.hash + "ntNonse: " + this.nonce + "n}" }
  • 58. class Blockchain { var chain = Seq[Block](createGenesisBlock()) val difficulty = 4 var pendingTransactions = Seq[Transaction]() val miningReward = 100 def createGenesisBlock(): Block = { new Block(LocalDateTime.now(), Seq(new Transaction("", "Initial Pool Address", 500))) }
  • 59. def addTransaction(transaction: Transaction): Unit = { this.pendingTransactions = this.pendingTransactions :+ transaction } def minePendingTransactions(rewardAddress: String): Unit = { val newBlock = new Block(LocalDateTime.now(), this.pendingTransactions) newBlock.mineBlock(this.difficulty) println("Block successfully mined: " + newBlock) this.chain = this.chain :+ newBlock this.pendingTransactions = Seq[Transaction](new Transaction("Reward", rewardAddress, this.miningReward)) }
  • 60. def getBalanceOfAddress(address: String): Double = { var balance = 0.0 this.chain.flatMap(block => block.transactions).foreach(transaction => { if(transaction.fromAddress == address) balance -= transaction.amount if(transaction.toAddress == address) balance += transaction.amount }) balance }
  • 61.
  • 62.
  • 63. • ✓ • Proof of Work ✓ ✓nonse Proof of Work ✓mining
  • 65. Satoshi Nakamoto (2009) Bitcoin: A Peer-to-Peer Electronic Cash System 2017 2018 Building a blockchain with Javascript