-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.go
More file actions
129 lines (113 loc) · 2.23 KB
/
Copy pathstorage.go
File metadata and controls
129 lines (113 loc) · 2.23 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"encoding/gob"
"os"
"errors"
)
func SaveChain(c *Blockchain) {
f, _ := os.Create("chain.db")
defer f.Close()
enc := gob.NewEncoder(f)
_ = enc.Encode(c)
}
func LoadChain() *Blockchain {
f, err := os.Open("chain.db")
if err != nil {
return nil
}
defer f.Close()
var c Blockchain
dec := gob.NewDecoder(f)
if err := dec.Decode(&c); err != nil {
return nil
}
return &c
}
func SaveWallets() {
f, _ := os.Create("wallets.db")
defer f.Close()
enc := gob.NewEncoder(f)
_ = enc.Encode(wallets)
}
func LoadWallets() {
f, err := os.Open("wallets.db")
if err != nil {
return
}
defer f.Close()
dec := gob.NewDecoder(f)
_ = dec.Decode(&wallets)
}
func SaveAll() {
SaveChain(chain)
SaveWallets()
}
//UTXO helpers & mempool (add to tx.go or storage)
func FindSpendableUTXOs(address string) (map[string][]int, int) {
utxos := map[string][]int{}
balance := 0
for _, b := range chain.Blocks {
for _, tx := range b.Transactions {
// outputs
for i, out := range tx.Vout {
if out.Address == address {
// check not spent by later txs
if !isSpent(tx.ID, i) {
utxos[tx.ID] = append(utxos[tx.ID], i)
balance += out.Amount
}
}
}
}
}
return utxos, balance
}
func isSpent(txid string, index int) bool {
for _, b := range chain.Blocks {
for _, tx := range b.Transactions {
for _, in := range tx.Vin {
if in.Txid == txid && in.OutIndex == index {
return true
}
}
}
}
return false
}
func GetOutputAmount(txid string, index int) int {
for _, b := range chain.Blocks {
for _, tx := range b.Transactions {
if tx.ID == txid {
return tx.Vout[index].Amount
}
}
}
return 0
}
func GetBalance(addr string) int {
_, bal := FindSpendableUTXOs(addr)
return bal
}
func CreateAndSignTx(from, to string, amount int) (*Transaction, error) {
tx, err := NewUTXOTransaction(from, to, amount)
if err != nil {
return nil, err
}
w, err := findWallet(from)
if err != nil {
return nil, err
}
SignTx(tx, w.Priv)
if !VerifyTx(tx) {
return nil, errors.New("tx verification failed")
}
return tx, nil
}
func mempoolAdd(tx *Transaction) error {
// simple check
if !VerifyTx(tx) {
return errors.New("invalid tx")
}
mempool = append(mempool, tx)
return nil
}