-
Notifications
You must be signed in to change notification settings - Fork 0
/
utxo.go
256 lines (225 loc) · 7.16 KB
/
utxo.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
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package wallet
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"github.com/bytom/bystack/account"
"github.com/bytom/bystack/consensus"
"github.com/bytom/bystack/consensus/segwit"
"github.com/bytom/bystack/crypto/sm3"
dbm "github.com/bytom/bystack/database/leveldb"
"github.com/bytom/bystack/errors"
"github.com/bytom/bystack/protocol/bc"
"github.com/bytom/bystack/protocol/bc/types"
)
// GetAccountUtxos return all account unspent outputs
func (w *Wallet) GetAccountUtxos(accountID string, id string, unconfirmed, isSmartContract, vote bool) []*account.UTXO {
prefix := account.UTXOPreFix
if isSmartContract {
prefix = account.SUTXOPrefix
}
accountUtxos := []*account.UTXO{}
if unconfirmed {
accountUtxos = w.AccountMgr.ListUnconfirmedUtxo(accountID, isSmartContract)
}
accountUtxoIter := w.DB.IteratorPrefix([]byte(prefix + id))
defer accountUtxoIter.Release()
for accountUtxoIter.Next() {
accountUtxo := &account.UTXO{}
if err := json.Unmarshal(accountUtxoIter.Value(), accountUtxo); err != nil {
log.WithFields(log.Fields{"module": logModule, "err": err}).Warn("GetAccountUtxos fail on unmarshal utxo")
continue
}
if vote && accountUtxo.Vote == nil {
continue
}
if accountID == accountUtxo.AccountID || accountID == "" {
accountUtxos = append(accountUtxos, accountUtxo)
}
}
return accountUtxos
}
func (w *Wallet) attachUtxos(batch dbm.Batch, b *types.Block) {
for _, tx := range b.Transactions {
// hand update the transaction input utxos
inputUtxos := txInToUtxos(tx)
for _, inputUtxo := range inputUtxos {
if segwit.IsP2WScript(inputUtxo.ControlProgram) {
batch.Delete(account.StandardUTXOKey(inputUtxo.OutputID))
} else {
batch.Delete(account.ContractUTXOKey(inputUtxo.OutputID))
}
}
// hand update the transaction output utxos
outputUtxos := txOutToUtxos(tx, b.Height)
utxos := w.filterAccountUtxo(outputUtxos)
if err := batchSaveUtxos(utxos, batch); err != nil {
log.WithFields(log.Fields{"module": logModule, "err": err}).Error("attachUtxos fail on batchSaveUtxos")
}
}
}
func (w *Wallet) detachUtxos(batch dbm.Batch, b *types.Block) {
for txIndex := len(b.Transactions) - 1; txIndex >= 0; txIndex-- {
tx := b.Transactions[txIndex]
for j := range tx.Outputs {
resOut, err := tx.OriginalOutput(*tx.ResultIds[j])
if err != nil {
continue
}
if segwit.IsP2WScript(resOut.ControlProgram.Code) {
batch.Delete(account.StandardUTXOKey(*tx.ResultIds[j]))
} else {
batch.Delete(account.ContractUTXOKey(*tx.ResultIds[j]))
}
}
inputUtxos := txInToUtxos(tx)
utxos := w.filterAccountUtxo(inputUtxos)
if err := batchSaveUtxos(utxos, batch); err != nil {
log.WithFields(log.Fields{"module": logModule, "err": err}).Error("detachUtxos fail on batchSaveUtxos")
return
}
}
}
func (w *Wallet) filterAccountUtxo(utxos []*account.UTXO) []*account.UTXO {
outsByScript := make(map[string][]*account.UTXO, len(utxos))
for _, utxo := range utxos {
scriptStr := string(utxo.ControlProgram)
outsByScript[scriptStr] = append(outsByScript[scriptStr], utxo)
}
result := make([]*account.UTXO, 0, len(utxos))
for s := range outsByScript {
if !segwit.IsP2WScript([]byte(s)) {
continue
}
var hash [32]byte
sm3.Sum(hash[:], []byte(s))
data := w.DB.Get(account.ContractKey(hash))
if data == nil {
continue
}
cp := &account.CtrlProgram{}
if err := json.Unmarshal(data, cp); err != nil {
log.WithFields(log.Fields{"module": logModule, "err": err}).Error("filterAccountUtxo fail on unmarshal control program")
continue
}
for _, utxo := range outsByScript[s] {
utxo.AccountID = cp.AccountID
utxo.Address = cp.Address
utxo.ControlProgramIndex = cp.KeyIndex
utxo.Change = cp.Change
result = append(result, utxo)
}
}
return result
}
func batchSaveUtxos(utxos []*account.UTXO, batch dbm.Batch) error {
for _, utxo := range utxos {
data, err := json.Marshal(utxo)
if err != nil {
return errors.Wrap(err, "failed marshal accountutxo")
}
if segwit.IsP2WScript(utxo.ControlProgram) {
batch.Set(account.StandardUTXOKey(utxo.OutputID), data)
} else {
batch.Set(account.ContractUTXOKey(utxo.OutputID), data)
}
}
return nil
}
func txInToUtxos(tx *types.Tx) []*account.UTXO {
utxos := []*account.UTXO{}
for _, inpID := range tx.Tx.InputIDs {
var utxo *account.UTXO
e, ok := tx.Entries[inpID]
if !ok {
continue
}
switch inp := e.(type) {
case *bc.Spend:
resOut, err := tx.OriginalOutput(*inp.SpentOutputId)
if err != nil {
log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txInToUtxos fail on get resOut")
continue
}
utxo = &account.UTXO{
OutputID: *inp.SpentOutputId,
AssetID: *resOut.Source.Value.AssetId,
Amount: resOut.Source.Value.Amount,
ControlProgram: resOut.ControlProgram.Code,
SourceID: *resOut.Source.Ref,
SourcePos: resOut.Source.Position,
}
case *bc.VetoInput:
resOut, err := tx.VoteOutput(*inp.SpentOutputId)
if err != nil {
log.WithFields(log.Fields{"module": logModule, "err": err}).Error("txInToUtxos fail on get resOut for vetoInput")
continue
}
if *resOut.Source.Value.AssetId != *consensus.BTMAssetID {
continue
}
utxo = &account.UTXO{
OutputID: *inp.SpentOutputId,
AssetID: *resOut.Source.Value.AssetId,
Amount: resOut.Source.Value.Amount,
ControlProgram: resOut.ControlProgram.Code,
SourceID: *resOut.Source.Ref,
SourcePos: resOut.Source.Position,
Vote: resOut.Vote,
}
default:
continue
}
utxos = append(utxos, utxo)
}
return utxos
}
func txOutToUtxos(tx *types.Tx, blockHeight uint64) []*account.UTXO {
utxos := []*account.UTXO{}
for i, out := range tx.Outputs {
validHeight := uint64(0)
entryOutput, ok := tx.Entries[*tx.ResultIds[i]]
if !ok {
log.WithFields(log.Fields{"module": logModule}).Error("txOutToUtxos fail on get entryOutput")
continue
}
var utxo *account.UTXO
switch bcOut := entryOutput.(type) {
case *bc.OriginalOutput:
if out.AssetAmount.Amount == uint64(0) {
continue
}
if tx.Inputs[0].InputType() == types.CoinbaseInputType {
validHeight = blockHeight + consensus.CoinbasePendingBlockNumber
}
utxo = &account.UTXO{
OutputID: *tx.OutputID(i),
AssetID: *out.AssetAmount.AssetId,
Amount: out.AssetAmount.Amount,
ControlProgram: out.ControlProgram,
SourceID: *bcOut.Source.Ref,
SourcePos: bcOut.Source.Position,
ValidHeight: validHeight,
}
case *bc.VoteOutput:
voteValidHeight := blockHeight + consensus.VotePendingBlockNums(blockHeight)
if validHeight < voteValidHeight {
validHeight = voteValidHeight
}
utxo = &account.UTXO{
OutputID: *tx.OutputID(i),
AssetID: *out.AssetAmount.AssetId,
Amount: out.AssetAmount.Amount,
ControlProgram: out.ControlProgram,
SourceID: *bcOut.Source.Ref,
SourcePos: bcOut.Source.Position,
ValidHeight: validHeight,
Vote: bcOut.Vote,
}
default:
log.WithFields(log.Fields{"module": logModule}).Warn("txOutToUtxos fail on get bcOut")
continue
}
utxos = append(utxos, utxo)
}
return utxos
}