Skip to content

How to make transaction id unique? #84

@guihao-liang

Description

@guihao-liang

I'm reading part 4, and I think if txid is not unique for this tutorial. Txid should be unique for blockchain. Otherwise, you can't lookup each transaction by txid.

The logic to generate txid. It generates the same id for newly mined coin:

func NewCoinbaseTX(to, data string) *Transaction {
if data == "" {
data = fmt.Sprintf("Reward to '%s'", to)
}
txin := TXInput{[]byte{}, -1, data}
txout := TXOutput{subsidy, to}
tx := Transaction{nil, []TXInput{txin}, []TXOutput{txout}}
tx.SetID()

the FindUnspentTransactions would go wrong:

if spentTXOs[txID] != nil {
for _, spentOut := range spentTXOs[txID] {
if spentOut == outIdx {
continue Outputs
}

for example, could you mine 2 new coins with duplicated txid by calling NewCoinbaseTX("same_miner", "")

Then one coin could be used and the other is not. The above FindUnspentTransactions logic can't distinguish those 2 coins.

Even if you add rand in part 6, it still has a chance of colliding.

func NewCoinbaseTX(to, data string) *Transaction {
if data == "" {
randData := make([]byte, 20)
_, err := rand.Read(randData)
if err != nil {
log.Panic(err)
}
data = fmt.Sprintf("%x", randData)
}
txin := TXInput{[]byte{}, -1, nil, []byte(data)}
txout := NewTXOutput(subsidy, to)
tx := Transaction{nil, []TXInput{txin}, []TXOutput{*txout}}
tx.ID = tx.Hash()

Any suggestion to make sure that the txid is unique?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions