1
0

Go言語でブロックチェーンのシステムを作成する(その3)

Last updated at Posted at 2024-03-31

はじめに

前回は、Block、Blockchainの作成、hashの実装までやりましたが、今回はtransactionsの実装をしていきます。

  • 前回までの記事

  • バージョン
    • Go 1.22.0

実装

イメージ図

下の図のPool、transactionsの実装をしていきます。

ブロックチェーン2.png

transactionsの実装

まず、transactionsの実装をしていきます。

type Transaction struct {
	senderBlockchainAddress    string
	recipientBlockchainAddress string
	value                      float32
}

func NewTransaction(sender string, recipient string, value float32) *Transaction {
	return &Transaction{sender, recipient, value}
}

func (t *Transaction) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		SenderBlockchainAddress    string  `json:"sender_blockchain_address"`
		RecipientBlockchainAddress string  `json:"recipient_blockchain_address"`
		Value                      float32 `json:"value"`
	}{
		SenderBlockchainAddress:    t.senderBlockchainAddress,
		RecipientBlockchainAddress: t.recipientBlockchainAddress,
		Value:                      t.value,
	})
}

Transactionは、senderBlockchainAddress、recipientBlockchainAddress、valueでstructを定義します。
NewTransactionでは、sender、recipient、valueの値を受け取り、Transactionを作成しています。
MarshalJSONは、前回もありましたが、json.Marshalをするために実装しています。

また、Transactionを定義したので、前回作成したコードでTransactionを使用している部分の修正をしていきます。

type Block struct {
    // stringから*Transactionに変更
	// transactions []string
	transactions []*Transaction
}

// 引数にtransactionsを追加
// func NewBlock(nonce int, previousHash [32]byte) *Block {
func NewBlock(nonce int, previousHash [32]byte, transactions []*Transaction) *Block {
	b := new(Block)
	b.timestamp = time.Now().UnixNano()
	b.nonce = nonce
	b.previousHash = previousHash
	b.transactions = transactions // 追加
	return b
}

func (b *Block) MarshalJSON() ([]byte, error) {
    // stringから*Transactionに変更
    // Transactions []string `json:"transactions"`
    Transactions []*Transaction `json:"transactions"`

type Blockchain struct {
    // stringから*Transactionに変更
    // transactionPool []string
	transactionPool []*Transaction
	chain           []*Block
}

func (bc *Blockchain) CreateBlock(nonce int, previousHash [32]byte) *Block {
    // bc.transactionPoolを引数に追加
    // b := NewBlock(nonce, previousHash)
	b := NewBlock(nonce, previousHash, bc.transactionPool)
	bc.chain = append(bc.chain, b)
	bc.transactionPool = []*Transaction{} // 追加
	return b
}

次に、TransactionをBlockchainのstructに追加するコードを実装します。

func (bc *Blockchain) AddTransaction(sender string, recipient string, value float32) {
	t := NewTransaction(sender, recipient, value)
	bc.transactionPool = append(bc.transactionPool, t)
}

AddTransactionでは、sender、recipient、valueの値を受け取り、Transactionを作成して、BlockchainのtransactionPoolに追加しています。

おわりに

今回は、transactionsの実装をしていきました。
次回は、nonceの実装をしていきます。

次の記事

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0