lemooljiang avatar

实现交易 / go实现简易区块链 #5

lemooljiang

Published: 27 Aug 2022 › Updated: 27 Aug 2022

实现交易 / go实现简易区块链 #5

在交易中我们把币送给其它人, 为了实现这个,需要创建一笔交易,把它设到区块中,然后挖出这个区块。

func NewUTXOTransaction(from, to string, amount int, bc *Blockchain) *Transaction {
    var inputs []TXInput
    var outputs []TXOutput
acc, validOutputs := bc.FindSpendableOutputs(from, amount)
if acc < amount {
        log.Panic("ERROR: Not enough funds")
    }
// Build a list of inputs
    for txid, outs := range validOutputs {
        txID, err := hex.DecodeString(txid)
for _, out := range outs {
            input := TXInput{txID, out, from}
            inputs = append(inputs, input)
        }
    }
// Build a list of outputs
    outputs = append(outputs, TXOutput{amount, to})
    if acc > amount {
        outputs = append(outputs, TXOutput{acc - amount, from}) // a change
    }
tx := Transaction{nil, inputs, outputs}
    tx.SetID()
return &tx
}

在创建新的output前,首先得找到所有有结余的output,也就是有足够的余额。FindSpendableOutputs方法负责做这事。

func (bc *Blockchain) FindSpendableOutputs(address string, amount int) (int, map[string][]int) {
    unspentOutputs := make(map[string][]int)
    unspentTXs := bc.FindUnspentTransactions(address)
    accumulated := 0
Work:
    for _, tx := range unspentTXs {
        txID := hex.EncodeToString(tx.ID)
for outIdx, out := range tx.Vout {
            if out.CanBeUnlockedWith(address) && accumulated < amount {
                accumulated += out.Value
                unspentOutputs[txID] = append(unspentOutputs[txID], outIdx)
if accumulated >= amount {
                    break Work
                }
            }
        }
    }
return accumulated, unspentOutputs
}

该方法遍历所有有结余的交易,汇总它们的值,当汇总的值等于或大于需要传送到其它地址的值时,就会停止查找,立即返回已经汇总到的值和以交易id分组的output索引数组。不需要找到比本次传送额更多的output。

最后,实现Send方法:

func (cli *CLI) send(from, to string, amount int) {
    bc := NewBlockchain(from)
    defer bc.db.Close()
tx := NewUTXOTransaction(from, to, amount, bc)
    bc.MineBlock([]*Transaction{tx})
    fmt.Println("Success!")
}

传送币到其它地址,这就是实现新的交易。在区块链网络中,会把所有的交易放到存储池中,按费用的多少排序打包,广播这些交易(确认)。

Leave 实现交易 / go实现简易区块链 #5 to:

Written by

Designer , Poet , Technology enthusiasts

Read more #cn posts


Best Posts From lemooljiang

We have not curated any of lemooljiang's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From lemooljiang