-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtransaction.go
88 lines (73 loc) · 1.79 KB
/
transaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"encoding/json"
"encoding/hex"
"crypto/sha256"
)
type Transaction struct {
Sender string
Receiver string
Amount uint64
Memo string
}
type TxMerkleTree struct {
RootNode *MerkleNode
}
type MerkleNode struct {
Left *MerkleNode
Right *MerkleNode
Data []byte
}
func NewMerkleNode(left *MerkleNode, right *MerkleNode, tx *Transaction) *MerkleNode {
mnode := MerkleNode{}
if left == nil && right == nil {
hash := sha256.Sum256(tx.Serialize())
mnode.Data = hash[:]
} else {
prevHashes := append(left.Data, right.Data...)
hash := sha256.Sum256(prevHashes)
mnode.Data = hash[:]
}
mnode.Left = left
mnode.Right = right
return &mnode
}
func BuildTxMerkleTree(txs []*Transaction) *TxMerkleTree {
var nodes []MerkleNode
node := NewMerkleNode(nil, nil, txs[0])
nodes = append(nodes, *node)
for i := 0; i < len(txs)/2; i++ {
var newLevel []MerkleNode
for j := 0; j < len(nodes); j += 2 {
node := NewMerkleNode(&nodes[j], &nodes[j+1], nil)
newLevel = append(newLevel, *node)
}
nodes = newLevel
}
mtree := TxMerkleTree{&nodes[0]}
return &mtree
}
////
func (tx *Transaction) Serialize() ([]byte){
data, err := json.Marshal(tx)
if err != nil {
panic(err)
}
return data
}
func DeserializeTx(buf []byte) (*Transaction, error){
var tx Transaction
err := json.Unmarshal(buf, &tx)
if err != nil {
return nil, err
}
return &tx, nil
}
func (tx *Transaction) GetTxid() ([32]byte) {
ser := tx.Serialize()
return sha256.Sum256(ser)
}
func (tx *Transaction) GetTxidString() string {
txid := tx.GetTxid()
return hex.EncodeToString(txid[:])
}