forked from BytomDAO/bytom
/
accounts.go
494 lines (415 loc) · 12.6 KB
/
accounts.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
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Package account stores and tracks accounts within a Bytom Core.
package account
import (
"context"
"encoding/json"
"strings"
"sync"
"time"
"github.com/golang/groupcache/lru"
log "github.com/sirupsen/logrus"
dbm "github.com/tendermint/tmlibs/db"
"github.com/bytom/blockchain/signers"
"github.com/bytom/blockchain/txbuilder"
"github.com/bytom/common"
"github.com/bytom/consensus"
"github.com/bytom/crypto"
"github.com/bytom/crypto/ed25519/chainkd"
"github.com/bytom/crypto/sha3pool"
"github.com/bytom/errors"
"github.com/bytom/protocol"
"github.com/bytom/protocol/vm/vmutil"
)
const (
maxAccountCache = 1000
)
var (
accountIndexKey = []byte("AccountIndex")
accountPrefix = []byte("Account:")
aliasPrefix = []byte("AccountAlias:")
contractIndexPrefix = []byte("ContractIndex")
contractPrefix = []byte("Contract:")
miningAddressKey = []byte("MiningAddress")
)
// pre-define errors for supporting bytom errorFormatter
var (
ErrDuplicateAlias = errors.New("duplicate account alias")
ErrFindAccount = errors.New("fail to find account")
ErrMarshalAccount = errors.New("failed marshal account")
ErrInvalidAddress = errors.New("invalid address")
ErrFindCtrlProgram = errors.New("fail to find account control program")
)
func aliasKey(name string) []byte {
return append(aliasPrefix, []byte(name)...)
}
// Key account store prefix
func Key(name string) []byte {
return append(accountPrefix, []byte(name)...)
}
// ContractKey account control promgram store prefix
func ContractKey(hash common.Hash) []byte {
return append(contractPrefix, hash[:]...)
}
func contractIndexKey(accountID string) []byte {
return append(contractIndexPrefix, []byte(accountID)...)
}
// NewManager creates a new account manager
func NewManager(walletDB dbm.DB, chain *protocol.Chain) *Manager {
return &Manager{
db: walletDB,
chain: chain,
utxoDB: newReserver(chain, walletDB),
cache: lru.New(maxAccountCache),
aliasCache: lru.New(maxAccountCache),
delayedACPs: make(map[*txbuilder.TemplateBuilder][]*CtrlProgram),
}
}
// Manager stores accounts and their associated control programs.
type Manager struct {
db dbm.DB
chain *protocol.Chain
utxoDB *reserver
cacheMu sync.Mutex
cache *lru.Cache
aliasCache *lru.Cache
delayedACPsMu sync.Mutex
delayedACPs map[*txbuilder.TemplateBuilder][]*CtrlProgram
accIndexMu sync.Mutex
accountMu sync.Mutex
}
// ExpireReservations removes reservations that have expired periodically.
// It blocks until the context is canceled.
func (m *Manager) ExpireReservations(ctx context.Context, period time.Duration) {
ticks := time.Tick(period)
for {
select {
case <-ctx.Done():
log.Info("Deposed, ExpireReservations exiting")
return
case <-ticks:
err := m.utxoDB.ExpireReservations(ctx)
if err != nil {
log.WithField("error", err).Error("Expire reservations")
}
}
}
}
// Account is structure of Bytom account
type Account struct {
*signers.Signer
ID string `json:"id"`
Alias string `json:"alias"`
}
func (m *Manager) getNextAccountIndex() uint64 {
m.accIndexMu.Lock()
defer m.accIndexMu.Unlock()
var nextIndex uint64 = 1
if rawIndexBytes := m.db.Get(accountIndexKey); rawIndexBytes != nil {
nextIndex = common.BytesToUnit64(rawIndexBytes) + 1
}
m.db.Set(accountIndexKey, common.Unit64ToBytes(nextIndex))
return nextIndex
}
func (m *Manager) getNextContractIndex(accountID string) uint64 {
m.accIndexMu.Lock()
defer m.accIndexMu.Unlock()
nextIndex := uint64(1)
if rawIndexBytes := m.db.Get(contractIndexKey(accountID)); rawIndexBytes != nil {
nextIndex = common.BytesToUnit64(rawIndexBytes) + 1
}
m.db.Set(contractIndexKey(accountID), common.Unit64ToBytes(nextIndex))
return nextIndex
}
// Create creates a new Account.
func (m *Manager) Create(ctx context.Context, xpubs []chainkd.XPub, quorum int, alias string) (*Account, error) {
m.accountMu.Lock()
defer m.accountMu.Unlock()
normalizedAlias := strings.ToLower(strings.TrimSpace(alias))
if existed := m.db.Get(aliasKey(normalizedAlias)); existed != nil {
return nil, ErrDuplicateAlias
}
signer, err := signers.Create("account", xpubs, quorum, m.getNextAccountIndex())
id := signers.IDGenerate()
if err != nil {
return nil, errors.Wrap(err)
}
account := &Account{Signer: signer, ID: id, Alias: normalizedAlias}
rawAccount, err := json.Marshal(account)
if err != nil {
return nil, ErrMarshalAccount
}
storeBatch := m.db.NewBatch()
accountID := Key(id)
storeBatch.Set(accountID, rawAccount)
storeBatch.Set(aliasKey(normalizedAlias), []byte(id))
storeBatch.Write()
return account, nil
}
// FindByAlias retrieves an account's Signer record by its alias
func (m *Manager) FindByAlias(ctx context.Context, alias string) (*Account, error) {
m.cacheMu.Lock()
cachedID, ok := m.aliasCache.Get(alias)
m.cacheMu.Unlock()
if ok {
return m.FindByID(ctx, cachedID.(string))
}
rawID := m.db.Get(aliasKey(alias))
if rawID == nil {
return nil, ErrFindAccount
}
accountID := string(rawID)
m.cacheMu.Lock()
m.aliasCache.Add(alias, accountID)
m.cacheMu.Unlock()
return m.FindByID(ctx, accountID)
}
// FindByID returns an account's Signer record by its ID.
func (m *Manager) FindByID(ctx context.Context, id string) (*Account, error) {
m.cacheMu.Lock()
cachedAccount, ok := m.cache.Get(id)
m.cacheMu.Unlock()
if ok {
return cachedAccount.(*Account), nil
}
rawAccount := m.db.Get(Key(id))
if rawAccount == nil {
return nil, ErrFindAccount
}
account := &Account{}
if err := json.Unmarshal(rawAccount, account); err != nil {
return nil, err
}
m.cacheMu.Lock()
m.cache.Add(id, account)
m.cacheMu.Unlock()
return account, nil
}
// GetAliasByID return the account alias by given ID
func (m *Manager) GetAliasByID(id string) string {
account := &Account{}
rawAccount := m.db.Get(Key(id))
if rawAccount == nil {
log.Warn("fail to find account")
return ""
}
if err := json.Unmarshal(rawAccount, account); err != nil {
log.Warn(err)
return ""
}
return account.Alias
}
// CreateAddress generate an address for the select account
func (m *Manager) CreateAddress(ctx context.Context, accountID string, change bool) (cp *CtrlProgram, err error) {
account, err := m.FindByID(ctx, accountID)
if err != nil {
return nil, err
}
return m.createAddress(ctx, account, change)
}
// CreateAddress generate an address for the select account
func (m *Manager) createAddress(ctx context.Context, account *Account, change bool) (cp *CtrlProgram, err error) {
if len(account.XPubs) == 1 {
cp, err = m.createP2PKH(ctx, account, change)
} else {
cp, err = m.createP2SH(ctx, account, change)
}
if err != nil {
return nil, err
}
if err = m.insertAccountControlProgram(ctx, cp); err != nil {
return nil, err
}
return cp, nil
}
func (m *Manager) createP2PKH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
idx := m.getNextContractIndex(account.ID)
path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
derivedPK := derivedXPubs[0].PublicKey()
pubHash := crypto.Ripemd160(derivedPK)
// TODO: pass different params due to config
address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
if err != nil {
return nil, err
}
control, err := vmutil.P2WPKHProgram([]byte(pubHash))
if err != nil {
return nil, err
}
return &CtrlProgram{
AccountID: account.ID,
Address: address.EncodeAddress(),
KeyIndex: idx,
ControlProgram: control,
Change: change,
}, nil
}
func (m *Manager) createP2SH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
idx := m.getNextContractIndex(account.ID)
path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
derivedPKs := chainkd.XPubKeys(derivedXPubs)
signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
if err != nil {
return nil, err
}
scriptHash := crypto.Sha256(signScript)
// TODO: pass different params due to config
address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
if err != nil {
return nil, err
}
control, err := vmutil.P2WSHProgram(scriptHash)
if err != nil {
return nil, err
}
return &CtrlProgram{
AccountID: account.ID,
Address: address.EncodeAddress(),
KeyIndex: idx,
ControlProgram: control,
Change: change,
}, nil
}
//CtrlProgram is structure of account control program
type CtrlProgram struct {
AccountID string
Address string
KeyIndex uint64
ControlProgram []byte
Change bool // Mark whether this control program is for UTXO change
}
func (m *Manager) insertAccountControlProgram(ctx context.Context, progs ...*CtrlProgram) error {
var hash common.Hash
for _, prog := range progs {
accountCP, err := json.Marshal(prog)
if err != nil {
return err
}
sha3pool.Sum256(hash[:], prog.ControlProgram)
m.db.Set(ContractKey(hash), accountCP)
}
return nil
}
// IsLocalControlProgram check is the input control program belong to local
func (m *Manager) IsLocalControlProgram(prog []byte) bool {
var hash common.Hash
sha3pool.Sum256(hash[:], prog)
bytes := m.db.Get(ContractKey(hash))
return bytes != nil
}
// GetCoinbaseControlProgram will return a coinbase script
func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
if data := m.db.Get(miningAddressKey); data != nil {
cp := &CtrlProgram{}
return cp.ControlProgram, json.Unmarshal(data, cp)
}
accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
defer accountIter.Release()
if !accountIter.Next() {
log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
return vmutil.DefaultCoinbaseProgram()
}
account := &Account{}
if err := json.Unmarshal(accountIter.Value(), account); err != nil {
return nil, err
}
program, err := m.createAddress(nil, account, false)
if err != nil {
return nil, err
}
rawCP, err := json.Marshal(program)
if err != nil {
return nil, err
}
m.db.Set(miningAddressKey, rawCP)
return program.ControlProgram, nil
}
// DeleteAccount deletes the account's ID or alias matching accountInfo.
func (m *Manager) DeleteAccount(aliasOrID string) (err error) {
account := &Account{}
if account, err = m.FindByAlias(nil, aliasOrID); err != nil {
if account, err = m.FindByID(nil, aliasOrID); err != nil {
return err
}
}
storeBatch := m.db.NewBatch()
m.cacheMu.Lock()
m.aliasCache.Remove(account.Alias)
m.cacheMu.Unlock()
storeBatch.Delete(aliasKey(account.Alias))
storeBatch.Delete(Key(account.ID))
storeBatch.Write()
return nil
}
// ListAccounts will return the accounts in the db
func (m *Manager) ListAccounts(id string) ([]*Account, error) {
accounts := []*Account{}
accountIter := m.db.IteratorPrefix(Key(strings.TrimSpace(id)))
defer accountIter.Release()
for accountIter.Next() {
account := &Account{}
if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
return nil, err
}
accounts = append(accounts, account)
}
return accounts, nil
}
// ListControlProgram return all the local control program
func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
var cps []*CtrlProgram
cpIter := m.db.IteratorPrefix(contractPrefix)
defer cpIter.Release()
for cpIter.Next() {
cp := &CtrlProgram{}
if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
return nil, err
}
cps = append(cps, cp)
}
return cps, nil
}
// GetProgramByAddress return CtrlProgram by given address
func (m *Manager) GetProgramByAddress(address string) (*CtrlProgram, error) {
addr, err := common.DecodeAddress(address, &consensus.ActiveNetParams)
if err != nil {
return nil, err
}
redeemContract := addr.ScriptAddress()
program := []byte{}
switch addr.(type) {
case *common.AddressWitnessPubKeyHash:
program, err = vmutil.P2WPKHProgram(redeemContract)
case *common.AddressWitnessScriptHash:
program, err = vmutil.P2WSHProgram(redeemContract)
default:
return nil, ErrInvalidAddress
}
if err != nil {
return nil, err
}
var hash [32]byte
cp := &CtrlProgram{}
sha3pool.Sum256(hash[:], program)
rawProgram := m.db.Get(ContractKey(hash))
if rawProgram == nil {
return nil, ErrFindCtrlProgram
}
if err := json.Unmarshal(rawProgram, cp); err != nil {
return nil, err
}
return cp, nil
}
// GetAccountByProgram return Account by given CtrlProgram
func (m *Manager) GetAccountByProgram(program *CtrlProgram) (*Account, error) {
rawAccount := m.db.Get(Key(program.AccountID))
if rawAccount == nil {
return nil, ErrFindAccount
}
account := &Account{}
if err := json.Unmarshal(rawAccount, account); err != nil {
return nil, err
}
return account, nil
}