-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathspvwallet.go
More file actions
379 lines (324 loc) · 9.23 KB
/
spvwallet.go
File metadata and controls
379 lines (324 loc) · 9.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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package main
import (
"bytes"
"encoding/hex"
"fmt"
"github.com/elastos/Elastos.ELA.SPV/bloom"
"github.com/elastos/Elastos.ELA.SPV/database"
"github.com/elastos/Elastos.ELA.SPV/sdk"
"github.com/elastos/Elastos.ELA.SPV/util"
"github.com/elastos/Elastos.ELA.SPV/wallet/store/headers"
"github.com/elastos/Elastos.ELA.SPV/wallet/store/sqlite"
"github.com/elastos/Elastos.ELA.SPV/wallet/sutil"
"github.com/elastos/Elastos.ELA/core"
"io"
"github.com/elastos/Elastos.ELA/common"
"github.com/elastos/Elastos.ELA/common/config"
tx "github.com/elastos/Elastos.ELA/core/transaction"
types "github.com/elastos/Elastos.ELA/core/types/common"
"github.com/elastos/Elastos.ELA/elanet/filter"
"github.com/elastos/Elastos.ELA/p2p/msg"
"github.com/elastos/Elastos.ELA/utils/http"
"github.com/elastos/Elastos.ELA/utils/http/jsonrpc"
)
const (
MaxPeers = 12
)
var ErrInvalidParameter = fmt.Errorf("invalide parameter")
type spvwallet struct {
sdk.IService
db sqlite.DataStore
filter *sdk.AddrFilter
}
func (w *spvwallet) putTx(batch sqlite.DataBatch, utx util.Transaction,
height uint32) (bool, error) {
tx := utx.(*sutil.Tx)
txId := tx.Hash()
hits := 0
// Check if any UTXOs within this wallet have been spent.
for _, input := range tx.Inputs() {
// Move UTXO to STXO
op := util.NewOutPoint(input.Previous.TxID, input.Previous.Index)
utxo, _ := w.db.UTXOs().Get(op)
// Skip if no match.
if utxo == nil {
continue
}
err := batch.STXOs().Put(sutil.NewSTXO(utxo, height, txId))
if err != nil {
return false, nil
}
hits++
}
// Check if there are any output to this wallet address.
for index, output := range tx.Outputs() {
// Filter address
if w.getAddrFilter().ContainAddr(output.ProgramHash) {
var lockTime = output.OutputLock
if tx.TxType() == types.CoinBase {
lockTime = height + 100
}
utxo := sutil.NewUTXO(txId, height, index, output.Value, lockTime, output.ProgramHash)
err := batch.UTXOs().Put(utxo)
if err != nil {
return false, err
}
hits++
}
}
// If no hits, no need to save transaction
if hits == 0 {
return true, nil
}
// Save transaction
err := batch.Txs().Put(util.NewTx(tx, height))
if err != nil {
return false, err
}
return false, nil
}
// PutTxs persists the main chain transactions into database and can be
// queried by GetTxs(height). Returns the false positive transaction count
// and error.
func (w *spvwallet) PutTxs(txs []util.Transaction, height uint32) (uint32, error) {
fps := uint32(0)
batch := w.db.Batch()
defer batch.Rollback()
for _, tx := range txs {
fp, err := w.putTx(batch, tx, height)
if err != nil {
return 0, err
}
if fp {
fps++
}
}
if err := batch.Commit(); err != nil {
return 0, err
}
return fps, nil
}
// PutForkTxs persists the fork chain transactions into database with the
// fork block hash and can be queried by GetForkTxs(hash).
func (w *spvwallet) PutForkTxs(txs []util.Transaction, hash *common.Uint256) error {
ftxs := make([]*util.Tx, 0, len(txs))
for _, tx := range txs {
ftxs = append(ftxs, util.NewTx(tx, 0))
}
return w.db.Txs().PutForkTxs(ftxs, hash)
}
// HaveTx returns if the transaction already saved in database
// by it's id.
func (w *spvwallet) HaveTx(txId *common.Uint256) (bool, error) {
tx, err := w.db.Txs().Get(txId)
return tx != nil, err
}
// GetTxs returns all transactions in main chain within the given height.
func (w *spvwallet) GetTxs(height uint32) ([]util.Transaction, error) {
txs, err := w.db.Txs().GetAllFrom(height)
if err != nil {
return nil, err
}
utxs := make([]util.Transaction, 0, len(txs))
for _, tx := range txs {
r := bytes.NewReader(tx.RawData)
wtx := newTransaction(r)
if err := wtx.Deserialize(r); err != nil {
return nil, err
}
utxs = append(utxs, wtx)
}
return utxs, nil
}
// GetForkTxs returns all transactions within the fork block hash.
func (w *spvwallet) GetForkTxs(hash *common.Uint256) ([]util.Transaction, error) {
ftxs, err := w.db.Txs().GetForkTxs(hash)
if err != nil {
return nil, err
}
txs := make([]util.Transaction, 0, len(ftxs))
for _, ftx := range ftxs {
r := bytes.NewReader(ftx.RawData)
tx := newTransaction(r)
if err := tx.Deserialize(r); err != nil {
return nil, err
}
txs = append(txs, tx)
}
return txs, nil
}
// DelTxs remove all transactions in main chain within the given height.
func (w *spvwallet) DelTxs(height uint32) error {
batch := w.db.Batch()
defer batch.Rollback()
if err := batch.RollbackHeight(height); err != nil {
return err
}
return batch.Commit()
}
// Clear delete all data in database.
func (w *spvwallet) Clear() error {
return w.db.Clear()
}
// Close database.
func (w *spvwallet) Close() error {
return w.db.Close()
}
func (w *spvwallet) GetFilter() *msg.TxFilterLoad {
utxos, err := w.db.UTXOs().GetAll()
if err != nil {
waltlog.Debugf("GetAll UTXOs error: %v", err)
}
stxos, err := w.db.STXOs().GetAll()
if err != nil {
waltlog.Debugf("GetAll STXOs error: %v", err)
}
outpoints := make([]*util.OutPoint, 0, len(utxos)+len(stxos))
for _, utxo := range utxos {
outpoints = append(outpoints, utxo.Op)
}
for _, stxo := range stxos {
outpoints = append(outpoints, stxo.Op)
}
addrs := w.getAddrFilter().GetAddrs()
elements := uint32(len(addrs) + len(outpoints))
f := bloom.NewFilter(elements, 0, 0, nil)
for _, addr := range addrs {
f.Add(addr.Bytes())
}
for _, op := range outpoints {
f.Add(op.Bytes())
}
return f.ToTxFilterMsg(filter.FTNexTTurnDPOSInfo)
}
func (w *spvwallet) NotifyNewAddress(hash []byte) {
// Reload address filter to include new address
w.loadAddrFilter()
// Broadcast filterload message to connected peers
w.UpdateFilter()
}
func (w *spvwallet) getAddrFilter() *sdk.AddrFilter {
if w.filter == nil {
w.loadAddrFilter()
}
return w.filter
}
func (w *spvwallet) loadAddrFilter() *sdk.AddrFilter {
addrs, _ := w.db.Addrs().GetAll()
w.filter = sdk.NewAddrFilter(nil)
for _, addr := range addrs {
w.filter.AddAddr(addr.Hash())
}
return w.filter
}
// TransactionAnnounce will be invoked when received a new announced transaction.
func (w *spvwallet) TransactionAnnounce(tx util.Transaction) {
// TODO
}
// TransactionAccepted will be invoked after a transaction sent by
// SendTransaction() method has been accepted. Notice: this method needs at
// lest two connected peers to work.
func (w *spvwallet) TransactionAccepted(tx util.Transaction) {
// TODO
}
// TransactionRejected will be invoked if a transaction sent by SendTransaction()
// method has been rejected.
func (w *spvwallet) TransactionRejected(tx util.Transaction) {
// TODO
}
// TransactionConfirmed will be invoked after a transaction sent by
// SendTransaction() method has been packed into a block.
func (w *spvwallet) TransactionConfirmed(tx *util.Tx) {
// TODO
}
// BlockCommitted will be invoked when a block and transactions within it are
// successfully committed into database.
func (w *spvwallet) BlockCommitted(block *util.Block) {
if !w.IsCurrent() {
return
}
w.db.State().PutHeight(block.Height)
// TODO
}
// Functions for RPC service.
func (w *spvwallet) notifyNewAddress(params http.Params) (interface{}, error) {
addrStr, ok := params.String("addr")
if !ok {
return nil, ErrInvalidParameter
}
address, err := common.Uint168FromAddress(addrStr)
if err != nil {
return nil, err
}
waltlog.Debugf("receive notifyNewAddress %s", address)
// Reload address filter to include new address
w.loadAddrFilter()
// Broadcast filterload message to connected peers
w.UpdateFilter()
return nil, nil
}
func (w *spvwallet) sendTransaction(params http.Params) (interface{}, error) {
data, ok := params.String("data")
if !ok {
return nil, ErrInvalidParameter
}
txBytes, err := hex.DecodeString(data)
if err != nil {
return nil, ErrInvalidParameter
}
r := bytes.NewReader(txBytes)
var tx = newTransaction(r)
err = tx.Deserialize(r)
if err != nil {
return nil, fmt.Errorf("deserialize transaction failed %s", err)
}
return nil, w.SendTransaction(tx)
}
func NewWallet(dataDir string) (*spvwallet, error) {
// Initialize headers db
headers, err := headers.NewDatabase(dataDir)
if err != nil {
return nil, err
}
db, err := sqlite.NewDatabase(dataDir)
if err != nil {
return nil, err
}
w := spvwallet{db: db}
chainStore := database.NewChainDB(headers, &w)
var params *config.Configuration
switch cfg.Network {
case "testnet", "test", "t":
params = config.DefaultParams.TestNet()
case "regnet", "reg", "r":
params = config.DefaultParams.RegNet()
default:
params = &config.DefaultParams
}
// Initialize spv service
w.IService, err = sdk.NewService(&sdk.Config{
ChainParams: params,
PermanentPeers: cfg.PermanentPeers,
GenesisHeader: sutil.NewHeader(&core.GenesisBlock(*params.FoundationProgramHash).Header),
ChainStore: chainStore,
NewTransaction: newTransaction,
NewBlockHeader: sutil.NewEmptyHeader,
GetTxFilter: w.GetFilter,
StateNotifier: &w,
})
if err != nil {
return nil, err
}
s := jsonrpc.NewServer(&jsonrpc.Config{
Path: "/spvwallet",
ServePort: cfg.RPCPort,
})
s.RegisterAction("notifynewaddress", w.notifyNewAddress, "addr")
s.RegisterAction("sendrawtransaction", w.sendTransaction, "data")
go s.Start()
return &w, nil
}
func newTransaction(r io.Reader) util.Transaction {
tx, _ := tx.GetTransactionByBytes(r)
return sutil.NewTx(tx)
}