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

in hive-180932 •  2 years ago 

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

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!")
}

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

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Google is paying $27485 to $29658 consistently for taking a shot at the web from home. I joined this action 2 months back and I have earned $31547 in my first month from this action. I can say my life has improved completely! Take a gander at what I do....http://MaxYourWealth.gq/