OSDN Git Service

Optimize log printing (#1590)
[bytom/bytom.git] / account / accounts.go
1 // Package account stores and tracks accounts within a Bytom Core.
2 package account
3
4 import (
5         "encoding/json"
6         "reflect"
7         "sort"
8         "strings"
9         "sync"
10
11         "github.com/golang/groupcache/lru"
12         log "github.com/sirupsen/logrus"
13         dbm "github.com/tendermint/tmlibs/db"
14
15         "github.com/bytom/blockchain/signers"
16         "github.com/bytom/blockchain/txbuilder"
17         "github.com/bytom/common"
18         "github.com/bytom/consensus"
19         "github.com/bytom/consensus/segwit"
20         "github.com/bytom/crypto"
21         "github.com/bytom/crypto/ed25519/chainkd"
22         "github.com/bytom/crypto/sha3pool"
23         "github.com/bytom/errors"
24         "github.com/bytom/protocol"
25         "github.com/bytom/protocol/bc"
26         "github.com/bytom/protocol/vm/vmutil"
27 )
28
29 const (
30         maxAccountCache = 1000
31
32         // HardenedKeyStart bip32 hierarchical deterministic wallets
33         // keys with index ≥ 0x80000000 are hardened keys
34         HardenedKeyStart = 0x80000000
35         logModule        = "account"
36 )
37
38 var (
39         accountIndexPrefix  = []byte("AccountIndex:")
40         accountPrefix       = []byte("Account:")
41         aliasPrefix         = []byte("AccountAlias:")
42         contractIndexPrefix = []byte("ContractIndex")
43         contractPrefix      = []byte("Contract:")
44         miningAddressKey    = []byte("MiningAddress")
45         CoinbaseAbKey       = []byte("CoinbaseArbitrary")
46 )
47
48 // pre-define errors for supporting bytom errorFormatter
49 var (
50         ErrDuplicateAlias  = errors.New("duplicate account alias")
51         ErrDuplicateIndex  = errors.New("duplicate account with same xPubs and index")
52         ErrFindAccount     = errors.New("fail to find account")
53         ErrMarshalAccount  = errors.New("failed marshal account")
54         ErrInvalidAddress  = errors.New("invalid address")
55         ErrFindCtrlProgram = errors.New("fail to find account control program")
56         ErrDeriveRule      = errors.New("invalid key derive rule")
57         ErrContractIndex   = errors.New("exceed the maximum addresses per account")
58         ErrAccountIndex    = errors.New("exceed the maximum accounts per xpub")
59         ErrFindTransaction = errors.New("no transaction")
60 )
61
62 // ContractKey account control promgram store prefix
63 func ContractKey(hash common.Hash) []byte {
64         return append(contractPrefix, hash[:]...)
65 }
66
67 // Key account store prefix
68 func Key(name string) []byte {
69         return append(accountPrefix, []byte(name)...)
70 }
71
72 func aliasKey(name string) []byte {
73         return append(aliasPrefix, []byte(name)...)
74 }
75
76 func bip44ContractIndexKey(accountID string, change bool) []byte {
77         key := append(contractIndexPrefix, accountID...)
78         if change {
79                 return append(key, []byte{1}...)
80         }
81         return append(key, []byte{0}...)
82 }
83
84 func contractIndexKey(accountID string) []byte {
85         return append(contractIndexPrefix, []byte(accountID)...)
86 }
87
88 // Account is structure of Bytom account
89 type Account struct {
90         *signers.Signer
91         ID    string `json:"id"`
92         Alias string `json:"alias"`
93 }
94
95 //CtrlProgram is structure of account control program
96 type CtrlProgram struct {
97         AccountID      string
98         Address        string
99         KeyIndex       uint64
100         ControlProgram []byte
101         Change         bool // Mark whether this control program is for UTXO change
102 }
103
104 // Manager stores accounts and their associated control programs.
105 type Manager struct {
106         db         dbm.DB
107         chain      *protocol.Chain
108         utxoKeeper *utxoKeeper
109
110         cacheMu    sync.Mutex
111         cache      *lru.Cache
112         aliasCache *lru.Cache
113
114         delayedACPsMu sync.Mutex
115         delayedACPs   map[*txbuilder.TemplateBuilder][]*CtrlProgram
116
117         addressMu sync.Mutex
118         accountMu sync.Mutex
119 }
120
121 // NewManager creates a new account manager
122 func NewManager(walletDB dbm.DB, chain *protocol.Chain) *Manager {
123         return &Manager{
124                 db:          walletDB,
125                 chain:       chain,
126                 utxoKeeper:  newUtxoKeeper(chain.BestBlockHeight, walletDB),
127                 cache:       lru.New(maxAccountCache),
128                 aliasCache:  lru.New(maxAccountCache),
129                 delayedACPs: make(map[*txbuilder.TemplateBuilder][]*CtrlProgram),
130         }
131 }
132
133 // AddUnconfirmedUtxo add untxo list to utxoKeeper
134 func (m *Manager) AddUnconfirmedUtxo(utxos []*UTXO) {
135         m.utxoKeeper.AddUnconfirmedUtxo(utxos)
136 }
137
138 // CreateAccount creates a new Account.
139 func CreateAccount(xpubs []chainkd.XPub, quorum int, alias string, acctIndex uint64, deriveRule uint8) (*Account, error) {
140         if acctIndex >= HardenedKeyStart {
141                 return nil, ErrAccountIndex
142         }
143
144         signer, err := signers.Create("account", xpubs, quorum, acctIndex, deriveRule)
145         if err != nil {
146                 return nil, errors.Wrap(err)
147         }
148
149         id := signers.IDGenerate()
150         return &Account{Signer: signer, ID: id, Alias: strings.ToLower(strings.TrimSpace(alias))}, nil
151 }
152
153 func (m *Manager) saveAccount(account *Account, updateIndex bool) error {
154         rawAccount, err := json.Marshal(account)
155         if err != nil {
156                 return ErrMarshalAccount
157         }
158
159         storeBatch := m.db.NewBatch()
160         storeBatch.Set(Key(account.ID), rawAccount)
161         storeBatch.Set(aliasKey(account.Alias), []byte(account.ID))
162         if updateIndex {
163                 storeBatch.Set(GetAccountIndexKey(account.XPubs), common.Unit64ToBytes(account.KeyIndex))
164         }
165         storeBatch.Write()
166         return nil
167 }
168
169 // SaveAccount save a new account.
170 func (m *Manager) SaveAccount(account *Account) error {
171         m.accountMu.Lock()
172         defer m.accountMu.Unlock()
173
174         if existed := m.db.Get(aliasKey(account.Alias)); existed != nil {
175                 return ErrDuplicateAlias
176         }
177
178         acct, err := m.GetAccountByXPubsIndex(account.XPubs, account.KeyIndex)
179         if err != nil {
180                 return err
181         }
182
183         if acct != nil {
184                 return ErrDuplicateIndex
185         }
186
187         currentIndex := uint64(0)
188         if rawIndexBytes := m.db.Get(GetAccountIndexKey(account.XPubs)); rawIndexBytes != nil {
189                 currentIndex = common.BytesToUnit64(rawIndexBytes)
190         }
191         return m.saveAccount(account, account.KeyIndex > currentIndex)
192 }
193
194 // Create creates and save a new Account.
195 func (m *Manager) Create(xpubs []chainkd.XPub, quorum int, alias string, deriveRule uint8) (*Account, error) {
196         m.accountMu.Lock()
197         defer m.accountMu.Unlock()
198
199         if existed := m.db.Get(aliasKey(alias)); existed != nil {
200                 return nil, ErrDuplicateAlias
201         }
202
203         acctIndex := uint64(1)
204         if rawIndexBytes := m.db.Get(GetAccountIndexKey(xpubs)); rawIndexBytes != nil {
205                 acctIndex = common.BytesToUnit64(rawIndexBytes) + 1
206         }
207         account, err := CreateAccount(xpubs, quorum, alias, acctIndex, deriveRule)
208         if err != nil {
209                 return nil, err
210         }
211
212         if err := m.saveAccount(account, true); err != nil {
213                 return nil, err
214         }
215
216         return account, nil
217 }
218
219 func (m *Manager) UpdateAccountAlias(accountID string, newAlias string) (err error) {
220         m.accountMu.Lock()
221         defer m.accountMu.Unlock()
222
223         account, err := m.FindByID(accountID)
224         if err != nil {
225                 return err
226         }
227         oldAlias := account.Alias
228
229         normalizedAlias := strings.ToLower(strings.TrimSpace(newAlias))
230         if existed := m.db.Get(aliasKey(normalizedAlias)); existed != nil {
231                 return ErrDuplicateAlias
232         }
233
234         m.cacheMu.Lock()
235         m.aliasCache.Remove(oldAlias)
236         m.cacheMu.Unlock()
237
238         account.Alias = normalizedAlias
239         rawAccount, err := json.Marshal(account)
240         if err != nil {
241                 return ErrMarshalAccount
242         }
243
244         storeBatch := m.db.NewBatch()
245         storeBatch.Delete(aliasKey(oldAlias))
246         storeBatch.Set(Key(accountID), rawAccount)
247         storeBatch.Set(aliasKey(normalizedAlias), []byte(accountID))
248         storeBatch.Write()
249         return nil
250 }
251
252 // CreateAddress generate an address for the select account
253 func (m *Manager) CreateAddress(accountID string, change bool) (cp *CtrlProgram, err error) {
254         m.addressMu.Lock()
255         defer m.addressMu.Unlock()
256
257         account, err := m.FindByID(accountID)
258         if err != nil {
259                 return nil, err
260         }
261
262         currentIdx, err := m.getCurrentContractIndex(account, change)
263         if err != nil {
264                 return nil, err
265         }
266
267         cp, err = CreateCtrlProgram(account, currentIdx+1, change)
268         if err != nil {
269                 return nil, err
270         }
271
272         return cp, m.saveControlProgram(cp, true)
273 }
274
275 // CreateBatchAddresses generate a batch of addresses for the select account
276 func (m *Manager) CreateBatchAddresses(accountID string, change bool, stopIndex uint64) error {
277         m.addressMu.Lock()
278         defer m.addressMu.Unlock()
279
280         account, err := m.FindByID(accountID)
281         if err != nil {
282                 return err
283         }
284
285         currentIndex, err := m.getCurrentContractIndex(account, change)
286         if err != nil {
287                 return err
288         }
289
290         for currentIndex++; currentIndex <= stopIndex; currentIndex++ {
291                 cp, err := CreateCtrlProgram(account, currentIndex, change)
292                 if err != nil {
293                         return err
294                 }
295
296                 if err := m.saveControlProgram(cp, true); err != nil {
297                         return err
298                 }
299         }
300
301         return nil
302 }
303
304 // deleteAccountControlPrograms deletes control program matching accountID
305 func (m *Manager) deleteAccountControlPrograms(accountID string) error {
306         cps, err := m.ListControlProgram()
307         if err != nil {
308                 return err
309         }
310
311         var hash common.Hash
312         for _, cp := range cps {
313                 if cp.AccountID == accountID {
314                         sha3pool.Sum256(hash[:], cp.ControlProgram)
315                         m.db.Delete(ContractKey(hash))
316                 }
317         }
318         return nil
319 }
320
321 // deleteAccountUtxos deletes utxos matching accountID
322 func (m *Manager) deleteAccountUtxos(accountID string) error {
323         accountUtxoIter := m.db.IteratorPrefix([]byte(UTXOPreFix))
324         defer accountUtxoIter.Release()
325         for accountUtxoIter.Next() {
326                 accountUtxo := &UTXO{}
327                 if err := json.Unmarshal(accountUtxoIter.Value(), accountUtxo); err != nil {
328                         return err
329                 }
330
331                 if accountID == accountUtxo.AccountID {
332                         m.db.Delete(StandardUTXOKey(accountUtxo.OutputID))
333                 }
334         }
335         return nil
336 }
337
338 // DeleteAccount deletes the account's ID or alias matching account ID.
339 func (m *Manager) DeleteAccount(accountID string) (err error) {
340         m.accountMu.Lock()
341         defer m.accountMu.Unlock()
342
343         account, err := m.FindByID(accountID)
344         if err != nil {
345                 return err
346         }
347
348         if err := m.deleteAccountControlPrograms(accountID); err != nil {
349                 return err
350         }
351         if err := m.deleteAccountUtxos(accountID); err != nil {
352                 return err
353         }
354
355         m.cacheMu.Lock()
356         m.aliasCache.Remove(account.Alias)
357         m.cacheMu.Unlock()
358
359         storeBatch := m.db.NewBatch()
360         storeBatch.Delete(aliasKey(account.Alias))
361         storeBatch.Delete(Key(account.ID))
362         storeBatch.Write()
363         return nil
364 }
365
366 // FindByAlias retrieves an account's Signer record by its alias
367 func (m *Manager) FindByAlias(alias string) (*Account, error) {
368         m.cacheMu.Lock()
369         cachedID, ok := m.aliasCache.Get(alias)
370         m.cacheMu.Unlock()
371         if ok {
372                 return m.FindByID(cachedID.(string))
373         }
374
375         rawID := m.db.Get(aliasKey(alias))
376         if rawID == nil {
377                 return nil, ErrFindAccount
378         }
379
380         accountID := string(rawID)
381         m.cacheMu.Lock()
382         m.aliasCache.Add(alias, accountID)
383         m.cacheMu.Unlock()
384         return m.FindByID(accountID)
385 }
386
387 // FindByID returns an account's Signer record by its ID.
388 func (m *Manager) FindByID(id string) (*Account, error) {
389         m.cacheMu.Lock()
390         cachedAccount, ok := m.cache.Get(id)
391         m.cacheMu.Unlock()
392         if ok {
393                 return cachedAccount.(*Account), nil
394         }
395
396         rawAccount := m.db.Get(Key(id))
397         if rawAccount == nil {
398                 return nil, ErrFindAccount
399         }
400
401         account := &Account{}
402         if err := json.Unmarshal(rawAccount, account); err != nil {
403                 return nil, err
404         }
405
406         m.cacheMu.Lock()
407         m.cache.Add(id, account)
408         m.cacheMu.Unlock()
409         return account, nil
410 }
411
412 // GetAccountByProgram return Account by given CtrlProgram
413 func (m *Manager) GetAccountByProgram(program *CtrlProgram) (*Account, error) {
414         rawAccount := m.db.Get(Key(program.AccountID))
415         if rawAccount == nil {
416                 return nil, ErrFindAccount
417         }
418
419         account := &Account{}
420         return account, json.Unmarshal(rawAccount, account)
421 }
422
423 // GetAccountByXPubsIndex get account by xPubs and index
424 func (m *Manager) GetAccountByXPubsIndex(xPubs []chainkd.XPub, index uint64) (*Account, error) {
425         accounts, err := m.ListAccounts("")
426         if err != nil {
427                 return nil, err
428         }
429
430         for _, account := range accounts {
431                 if reflect.DeepEqual(account.XPubs, xPubs) && account.KeyIndex == index {
432                         return account, nil
433                 }
434         }
435         return nil, nil
436 }
437
438 // GetAliasByID return the account alias by given ID
439 func (m *Manager) GetAliasByID(id string) string {
440         rawAccount := m.db.Get(Key(id))
441         if rawAccount == nil {
442                 log.Warn("GetAliasByID fail to find account")
443                 return ""
444         }
445
446         account := &Account{}
447         if err := json.Unmarshal(rawAccount, account); err != nil {
448                 log.Warn(err)
449         }
450         return account.Alias
451 }
452
453 func (m *Manager) GetCoinbaseArbitrary() []byte {
454         if arbitrary := m.db.Get(CoinbaseAbKey); arbitrary != nil {
455                 return arbitrary
456         }
457         return []byte{}
458 }
459
460 // GetCoinbaseControlProgram will return a coinbase script
461 func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
462         cp, err := m.GetCoinbaseCtrlProgram()
463         if err == ErrFindAccount {
464                 log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
465                 return vmutil.DefaultCoinbaseProgram()
466         }
467         if err != nil {
468                 return nil, err
469         }
470         return cp.ControlProgram, nil
471 }
472
473 // GetCoinbaseCtrlProgram will return the coinbase CtrlProgram
474 func (m *Manager) GetCoinbaseCtrlProgram() (*CtrlProgram, error) {
475         if data := m.db.Get(miningAddressKey); data != nil {
476                 cp := &CtrlProgram{}
477                 return cp, json.Unmarshal(data, cp)
478         }
479
480         accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
481         defer accountIter.Release()
482         if !accountIter.Next() {
483                 return nil, ErrFindAccount
484         }
485
486         account := &Account{}
487         if err := json.Unmarshal(accountIter.Value(), account); err != nil {
488                 return nil, err
489         }
490
491         program, err := m.CreateAddress(account.ID, false)
492         if err != nil {
493                 return nil, err
494         }
495
496         rawCP, err := json.Marshal(program)
497         if err != nil {
498                 return nil, err
499         }
500
501         m.db.Set(miningAddressKey, rawCP)
502         return program, nil
503 }
504
505 // GetContractIndex return the current index
506 func (m *Manager) GetContractIndex(accountID string) uint64 {
507         index := uint64(0)
508         if rawIndexBytes := m.db.Get(contractIndexKey(accountID)); rawIndexBytes != nil {
509                 index = common.BytesToUnit64(rawIndexBytes)
510         }
511         return index
512 }
513
514 // GetBip44ContractIndex return the current bip44 contract index
515 func (m *Manager) GetBip44ContractIndex(accountID string, change bool) uint64 {
516         index := uint64(0)
517         if rawIndexBytes := m.db.Get(bip44ContractIndexKey(accountID, change)); rawIndexBytes != nil {
518                 index = common.BytesToUnit64(rawIndexBytes)
519         }
520         return index
521 }
522
523 // GetLocalCtrlProgramByAddress return CtrlProgram by given address
524 func (m *Manager) GetLocalCtrlProgramByAddress(address string) (*CtrlProgram, error) {
525         program, err := m.getProgramByAddress(address)
526         if err != nil {
527                 return nil, err
528         }
529
530         var hash [32]byte
531         sha3pool.Sum256(hash[:], program)
532         rawProgram := m.db.Get(ContractKey(hash))
533         if rawProgram == nil {
534                 return nil, ErrFindCtrlProgram
535         }
536
537         cp := &CtrlProgram{}
538         return cp, json.Unmarshal(rawProgram, cp)
539 }
540
541 // GetMiningAddress will return the mining address
542 func (m *Manager) GetMiningAddress() (string, error) {
543         cp, err := m.GetCoinbaseCtrlProgram()
544         if err != nil {
545                 return "", err
546         }
547         return cp.Address, nil
548 }
549
550 // IsLocalControlProgram check is the input control program belong to local
551 func (m *Manager) IsLocalControlProgram(prog []byte) bool {
552         var hash common.Hash
553         sha3pool.Sum256(hash[:], prog)
554         bytes := m.db.Get(ContractKey(hash))
555         return bytes != nil
556 }
557
558 // ListAccounts will return the accounts in the db
559 func (m *Manager) ListAccounts(id string) ([]*Account, error) {
560         accounts := []*Account{}
561         accountIter := m.db.IteratorPrefix(Key(strings.TrimSpace(id)))
562         defer accountIter.Release()
563
564         for accountIter.Next() {
565                 account := &Account{}
566                 if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
567                         return nil, err
568                 }
569                 accounts = append(accounts, account)
570         }
571         return accounts, nil
572 }
573
574 // ListControlProgram return all the local control program
575 func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
576         cps := []*CtrlProgram{}
577         cpIter := m.db.IteratorPrefix(contractPrefix)
578         defer cpIter.Release()
579
580         for cpIter.Next() {
581                 cp := &CtrlProgram{}
582                 if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
583                         return nil, err
584                 }
585                 cps = append(cps, cp)
586         }
587         return cps, nil
588 }
589
590 func (m *Manager) ListUnconfirmedUtxo(accountID string, isSmartContract bool) []*UTXO {
591         utxos := m.utxoKeeper.ListUnconfirmed()
592         result := []*UTXO{}
593         for _, utxo := range utxos {
594                 if segwit.IsP2WScript(utxo.ControlProgram) != isSmartContract && (accountID == utxo.AccountID || accountID == "") {
595                         result = append(result, utxo)
596                 }
597         }
598         return result
599 }
600
601 // RemoveUnconfirmedUtxo remove utxos from the utxoKeeper
602 func (m *Manager) RemoveUnconfirmedUtxo(hashes []*bc.Hash) {
603         m.utxoKeeper.RemoveUnconfirmedUtxo(hashes)
604 }
605
606 // SetMiningAddress will set the mining address
607 func (m *Manager) SetMiningAddress(miningAddress string) (string, error) {
608         program, err := m.getProgramByAddress(miningAddress)
609         if err != nil {
610                 return "", err
611         }
612
613         cp := &CtrlProgram{
614                 Address:        miningAddress,
615                 ControlProgram: program,
616         }
617         rawCP, err := json.Marshal(cp)
618         if err != nil {
619                 return "", err
620         }
621
622         m.db.Set(miningAddressKey, rawCP)
623         return m.GetMiningAddress()
624 }
625
626 func (m *Manager) SetCoinbaseArbitrary(arbitrary []byte) {
627         m.db.Set(CoinbaseAbKey, arbitrary)
628 }
629
630 // CreateCtrlProgram generate an address for the select account
631 func CreateCtrlProgram(account *Account, addrIdx uint64, change bool) (cp *CtrlProgram, err error) {
632         path, err := signers.Path(account.Signer, signers.AccountKeySpace, change, addrIdx)
633         if err != nil {
634                 return nil, err
635         }
636
637         if len(account.XPubs) == 1 {
638                 cp, err = createP2PKH(account, path)
639         } else {
640                 cp, err = createP2SH(account, path)
641         }
642         if err != nil {
643                 return nil, err
644         }
645         cp.KeyIndex, cp.Change = addrIdx, change
646         return cp, nil
647 }
648
649 func createP2PKH(account *Account, path [][]byte) (*CtrlProgram, error) {
650         derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
651         derivedPK := derivedXPubs[0].PublicKey()
652         pubHash := crypto.Ripemd160(derivedPK)
653
654         address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
655         if err != nil {
656                 return nil, err
657         }
658
659         control, err := vmutil.P2WPKHProgram([]byte(pubHash))
660         if err != nil {
661                 return nil, err
662         }
663
664         return &CtrlProgram{
665                 AccountID:      account.ID,
666                 Address:        address.EncodeAddress(),
667                 ControlProgram: control,
668         }, nil
669 }
670
671 func createP2SH(account *Account, path [][]byte) (*CtrlProgram, error) {
672         derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
673         derivedPKs := chainkd.XPubKeys(derivedXPubs)
674         signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
675         if err != nil {
676                 return nil, err
677         }
678         scriptHash := crypto.Sha256(signScript)
679
680         address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
681         if err != nil {
682                 return nil, err
683         }
684
685         control, err := vmutil.P2WSHProgram(scriptHash)
686         if err != nil {
687                 return nil, err
688         }
689
690         return &CtrlProgram{
691                 AccountID:      account.ID,
692                 Address:        address.EncodeAddress(),
693                 ControlProgram: control,
694         }, nil
695 }
696
697 func GetAccountIndexKey(xpubs []chainkd.XPub) []byte {
698         var hash [32]byte
699         var xPubs []byte
700         cpy := append([]chainkd.XPub{}, xpubs[:]...)
701         sort.Sort(signers.SortKeys(cpy))
702         for _, xpub := range cpy {
703                 xPubs = append(xPubs, xpub[:]...)
704         }
705         sha3pool.Sum256(hash[:], xPubs)
706         return append(accountIndexPrefix, hash[:]...)
707 }
708
709 func (m *Manager) getCurrentContractIndex(account *Account, change bool) (uint64, error) {
710         switch account.DeriveRule {
711         case signers.BIP0032:
712                 return m.GetContractIndex(account.ID), nil
713         case signers.BIP0044:
714                 return m.GetBip44ContractIndex(account.ID, change), nil
715         }
716         return 0, ErrDeriveRule
717 }
718
719 func (m *Manager) getProgramByAddress(address string) ([]byte, error) {
720         addr, err := common.DecodeAddress(address, &consensus.ActiveNetParams)
721         if err != nil {
722                 return nil, err
723         }
724         redeemContract := addr.ScriptAddress()
725         program := []byte{}
726         switch addr.(type) {
727         case *common.AddressWitnessPubKeyHash:
728                 program, err = vmutil.P2WPKHProgram(redeemContract)
729         case *common.AddressWitnessScriptHash:
730                 program, err = vmutil.P2WSHProgram(redeemContract)
731         default:
732                 return nil, ErrInvalidAddress
733         }
734         if err != nil {
735                 return nil, err
736         }
737         return program, nil
738 }
739
740 func (m *Manager) saveControlProgram(prog *CtrlProgram, updateIndex bool) error {
741         var hash common.Hash
742
743         sha3pool.Sum256(hash[:], prog.ControlProgram)
744         acct, err := m.GetAccountByProgram(prog)
745         if err != nil {
746                 return err
747         }
748
749         accountCP, err := json.Marshal(prog)
750         if err != nil {
751                 return err
752         }
753
754         storeBatch := m.db.NewBatch()
755         storeBatch.Set(ContractKey(hash), accountCP)
756         if updateIndex {
757                 switch acct.DeriveRule {
758                 case signers.BIP0032:
759                         storeBatch.Set(contractIndexKey(acct.ID), common.Unit64ToBytes(prog.KeyIndex))
760                 case signers.BIP0044:
761                         storeBatch.Set(bip44ContractIndexKey(acct.ID, prog.Change), common.Unit64ToBytes(prog.KeyIndex))
762                 }
763         }
764         storeBatch.Write()
765
766         return nil
767 }
768
769 // SaveControlPrograms save account control programs
770 func (m *Manager) SaveControlPrograms(progs ...*CtrlProgram) error {
771         m.addressMu.Lock()
772         defer m.addressMu.Unlock()
773
774         for _, prog := range progs {
775                 acct, err := m.GetAccountByProgram(prog)
776                 if err != nil {
777                         return err
778                 }
779
780                 currentIndex, err := m.getCurrentContractIndex(acct, prog.Change)
781                 if err != nil {
782                         return err
783                 }
784
785                 m.saveControlProgram(prog, prog.KeyIndex > currentIndex)
786         }
787         return nil
788 }