1 // Package account stores and tracks accounts within a Bytom Core.
11 "github.com/golang/groupcache/lru"
12 log "github.com/sirupsen/logrus"
14 "github.com/vapor/blockchain/signers"
15 "github.com/vapor/blockchain/txbuilder"
16 "github.com/vapor/common"
17 "github.com/vapor/consensus"
18 "github.com/vapor/consensus/segwit"
19 "github.com/vapor/crypto"
20 "github.com/vapor/crypto/ed25519/chainkd"
21 "github.com/vapor/crypto/sha3pool"
22 dbm "github.com/vapor/database/leveldb"
23 "github.com/vapor/errors"
24 "github.com/vapor/protocol"
25 "github.com/vapor/protocol/bc"
26 "github.com/vapor/protocol/vm/vmutil"
30 maxAccountCache = 1000
32 // HardenedKeyStart bip32 hierarchical deterministic wallets
33 // keys with index ≥ 0x80000000 are hardened keys
34 HardenedKeyStart = 0x80000000
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")
48 // pre-define errors for supporting bytom errorFormatter
50 ErrDuplicateAlias = errors.New("Duplicate account alias")
51 ErrDuplicateIndex = errors.New("Duplicate account with same xPubs and index")
52 ErrFindAccount = errors.New("Failed to find account")
53 ErrMarshalAccount = errors.New("Failed to marshal account")
54 ErrInvalidAddress = errors.New("Invalid address")
55 ErrFindCtrlProgram = errors.New("Failed to find account control program")
56 ErrDeriveRule = errors.New("Invalid key derivation rule")
57 ErrContractIndex = errors.New("Exceeded maximum addresses per account")
58 ErrAccountIndex = errors.New("Exceeded maximum accounts per xpub")
59 ErrFindTransaction = errors.New("No transaction")
62 // ContractKey account control promgram store prefix
63 func ContractKey(hash common.Hash) []byte {
64 return append(contractPrefix, hash[:]...)
67 // Key account store prefix
68 func Key(name string) []byte {
69 return append(accountPrefix, []byte(name)...)
72 func aliasKey(name string) []byte {
73 return append(aliasPrefix, []byte(name)...)
76 func bip44ContractIndexKey(accountID string, change bool) []byte {
77 key := append(contractIndexPrefix, accountID...)
79 return append(key, []byte{1}...)
81 return append(key, []byte{0}...)
84 func contractIndexKey(accountID string) []byte {
85 return append(contractIndexPrefix, []byte(accountID)...)
88 // Account is structure of Bytom account
92 Alias string `json:"alias"`
95 //CtrlProgram is structure of account control program
96 type CtrlProgram struct {
100 ControlProgram []byte
101 Change bool // Mark whether this control program is for UTXO change
104 // Manager stores accounts and their associated control programs.
105 type Manager struct {
107 chain *protocol.Chain
108 utxoKeeper *utxoKeeper
112 aliasCache *lru.Cache
114 delayedACPsMu sync.Mutex
115 delayedACPs map[*txbuilder.TemplateBuilder][]*CtrlProgram
121 // NewManager creates a new account manager
122 func NewManager(walletDB dbm.DB, chain *protocol.Chain) *Manager {
126 utxoKeeper: newUtxoKeeper(chain.BestBlockHeight, walletDB),
127 cache: lru.New(maxAccountCache),
128 aliasCache: lru.New(maxAccountCache),
129 delayedACPs: make(map[*txbuilder.TemplateBuilder][]*CtrlProgram),
133 // AddUnconfirmedUtxo add untxo list to utxoKeeper
134 func (m *Manager) AddUnconfirmedUtxo(utxos []*UTXO) {
135 m.utxoKeeper.AddUnconfirmedUtxo(utxos)
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
144 signer, err := signers.Create("account", xpubs, quorum, acctIndex, deriveRule)
146 return nil, errors.Wrap(err)
149 id := signers.IDGenerate()
150 return &Account{Signer: signer, ID: id, Alias: strings.ToLower(strings.TrimSpace(alias))}, nil
153 func (m *Manager) saveAccount(account *Account, updateIndex bool) error {
154 rawAccount, err := json.Marshal(account)
156 return ErrMarshalAccount
159 storeBatch := m.db.NewBatch()
160 storeBatch.Set(Key(account.ID), rawAccount)
161 storeBatch.Set(aliasKey(account.Alias), []byte(account.ID))
163 storeBatch.Set(GetAccountIndexKey(account.XPubs), common.Unit64ToBytes(account.KeyIndex))
169 // SaveAccount save a new account.
170 func (m *Manager) SaveAccount(account *Account) error {
172 defer m.accountMu.Unlock()
174 if existed := m.db.Get(aliasKey(account.Alias)); existed != nil {
175 return ErrDuplicateAlias
178 acct, err := m.GetAccountByXPubsIndex(account.XPubs, account.KeyIndex)
184 return ErrDuplicateIndex
187 currentIndex := uint64(0)
188 if rawIndexBytes := m.db.Get(GetAccountIndexKey(account.XPubs)); rawIndexBytes != nil {
189 currentIndex = common.BytesToUnit64(rawIndexBytes)
191 return m.saveAccount(account, account.KeyIndex > currentIndex)
194 // Create creates and save a new Account.
195 func (m *Manager) Create(xpubs []chainkd.XPub, quorum int, alias string, deriveRule uint8) (*Account, error) {
197 defer m.accountMu.Unlock()
199 if existed := m.db.Get(aliasKey(alias)); existed != nil {
200 return nil, ErrDuplicateAlias
203 acctIndex := uint64(1)
204 if rawIndexBytes := m.db.Get(GetAccountIndexKey(xpubs)); rawIndexBytes != nil {
205 acctIndex = common.BytesToUnit64(rawIndexBytes) + 1
207 account, err := CreateAccount(xpubs, quorum, alias, acctIndex, deriveRule)
212 if err := m.saveAccount(account, true); err != nil {
219 func (m *Manager) UpdateAccountAlias(accountID string, newAlias string) (err error) {
221 defer m.accountMu.Unlock()
223 account, err := m.FindByID(accountID)
227 oldAlias := account.Alias
229 normalizedAlias := strings.ToLower(strings.TrimSpace(newAlias))
230 if existed := m.db.Get(aliasKey(normalizedAlias)); existed != nil {
231 return ErrDuplicateAlias
235 m.aliasCache.Remove(oldAlias)
238 account.Alias = normalizedAlias
239 rawAccount, err := json.Marshal(account)
241 return ErrMarshalAccount
244 storeBatch := m.db.NewBatch()
245 storeBatch.Delete(aliasKey(oldAlias))
246 storeBatch.Set(Key(accountID), rawAccount)
247 storeBatch.Set(aliasKey(normalizedAlias), []byte(accountID))
252 // CreateAddress generate an address for the select account
253 func (m *Manager) CreateAddress(accountID string, change bool) (cp *CtrlProgram, err error) {
255 defer m.addressMu.Unlock()
257 account, err := m.FindByID(accountID)
262 currentIdx, err := m.getCurrentContractIndex(account, change)
267 cp, err = CreateCtrlProgram(account, currentIdx+1, change)
272 return cp, m.saveControlProgram(cp, true)
275 // CreateBatchAddresses generate a batch of addresses for the select account
276 func (m *Manager) CreateBatchAddresses(accountID string, change bool, stopIndex uint64) error {
278 defer m.addressMu.Unlock()
280 account, err := m.FindByID(accountID)
285 currentIndex, err := m.getCurrentContractIndex(account, change)
290 for currentIndex++; currentIndex <= stopIndex; currentIndex++ {
291 cp, err := CreateCtrlProgram(account, currentIndex, change)
296 if err := m.saveControlProgram(cp, true); err != nil {
304 // deleteAccountControlPrograms deletes control program matching accountID
305 func (m *Manager) deleteAccountControlPrograms(accountID string) error {
306 cps, err := m.ListControlProgram()
312 for _, cp := range cps {
313 if cp.AccountID == accountID {
314 sha3pool.Sum256(hash[:], cp.ControlProgram)
315 m.db.Delete(ContractKey(hash))
318 m.db.Delete(bip44ContractIndexKey(accountID, false))
319 m.db.Delete(bip44ContractIndexKey(accountID, true))
320 m.db.Delete(contractIndexKey(accountID))
324 // deleteAccountUtxos deletes utxos matching accountID
325 func (m *Manager) deleteAccountUtxos(accountID string) error {
326 accountUtxoIter := m.db.IteratorPrefix([]byte(UTXOPreFix))
327 defer accountUtxoIter.Release()
328 for accountUtxoIter.Next() {
329 accountUtxo := &UTXO{}
330 if err := json.Unmarshal(accountUtxoIter.Value(), accountUtxo); err != nil {
334 if accountID == accountUtxo.AccountID {
335 m.db.Delete(StandardUTXOKey(accountUtxo.OutputID))
341 // DeleteAccount deletes the account's ID or alias matching account ID.
342 func (m *Manager) DeleteAccount(accountID string) (err error) {
344 defer m.accountMu.Unlock()
346 account, err := m.FindByID(accountID)
351 if err := m.deleteAccountControlPrograms(accountID); err != nil {
354 if err := m.deleteAccountUtxos(accountID); err != nil {
359 m.aliasCache.Remove(account.Alias)
362 storeBatch := m.db.NewBatch()
363 storeBatch.Delete(aliasKey(account.Alias))
364 storeBatch.Delete(Key(account.ID))
369 // FindByAlias retrieves an account's Signer record by its alias
370 func (m *Manager) FindByAlias(alias string) (*Account, error) {
372 cachedID, ok := m.aliasCache.Get(alias)
375 return m.FindByID(cachedID.(string))
378 rawID := m.db.Get(aliasKey(alias))
380 return nil, ErrFindAccount
383 accountID := string(rawID)
385 m.aliasCache.Add(alias, accountID)
387 return m.FindByID(accountID)
390 // FindByID returns an account's Signer record by its ID.
391 func (m *Manager) FindByID(id string) (*Account, error) {
393 cachedAccount, ok := m.cache.Get(id)
396 return cachedAccount.(*Account), nil
399 rawAccount := m.db.Get(Key(id))
400 if rawAccount == nil {
401 return nil, ErrFindAccount
404 account := &Account{}
405 if err := json.Unmarshal(rawAccount, account); err != nil {
410 m.cache.Add(id, account)
415 // GetAccountByProgram return Account by given CtrlProgram
416 func (m *Manager) GetAccountByProgram(program *CtrlProgram) (*Account, error) {
417 rawAccount := m.db.Get(Key(program.AccountID))
418 if rawAccount == nil {
419 return nil, ErrFindAccount
422 account := &Account{}
423 return account, json.Unmarshal(rawAccount, account)
426 // GetAccountByXPubsIndex get account by xPubs and index
427 func (m *Manager) GetAccountByXPubsIndex(xPubs []chainkd.XPub, index uint64) (*Account, error) {
428 accounts, err := m.ListAccounts("")
433 for _, account := range accounts {
434 if reflect.DeepEqual(account.XPubs, xPubs) && account.KeyIndex == index {
441 // GetAliasByID return the account alias by given ID
442 func (m *Manager) GetAliasByID(id string) string {
443 rawAccount := m.db.Get(Key(id))
444 if rawAccount == nil {
445 log.Warn("GetAliasByID fail to find account")
449 account := &Account{}
450 if err := json.Unmarshal(rawAccount, account); err != nil {
456 func (m *Manager) GetCoinbaseArbitrary() []byte {
457 if arbitrary := m.db.Get(CoinbaseAbKey); arbitrary != nil {
463 // GetCoinbaseControlProgram will return a coinbase script
464 func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
465 cp, err := m.GetCoinbaseCtrlProgram()
466 if err == ErrFindAccount {
467 log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
468 return vmutil.DefaultCoinbaseProgram()
473 return cp.ControlProgram, nil
476 // GetCoinbaseCtrlProgram will return the coinbase CtrlProgram
477 func (m *Manager) GetCoinbaseCtrlProgram() (*CtrlProgram, error) {
478 if data := m.db.Get(miningAddressKey); data != nil {
480 return cp, json.Unmarshal(data, cp)
483 accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
484 defer accountIter.Release()
485 if !accountIter.Next() {
486 return nil, ErrFindAccount
489 account := &Account{}
490 if err := json.Unmarshal(accountIter.Value(), account); err != nil {
494 program, err := m.CreateAddress(account.ID, false)
499 rawCP, err := json.Marshal(program)
504 m.db.Set(miningAddressKey, rawCP)
508 // GetContractIndex return the current index
509 func (m *Manager) GetContractIndex(accountID string) uint64 {
511 if rawIndexBytes := m.db.Get(contractIndexKey(accountID)); rawIndexBytes != nil {
512 index = common.BytesToUnit64(rawIndexBytes)
517 // GetBip44ContractIndex return the current bip44 contract index
518 func (m *Manager) GetBip44ContractIndex(accountID string, change bool) uint64 {
520 if rawIndexBytes := m.db.Get(bip44ContractIndexKey(accountID, change)); rawIndexBytes != nil {
521 index = common.BytesToUnit64(rawIndexBytes)
526 // GetLocalCtrlProgramByAddress return CtrlProgram by given address
527 func (m *Manager) GetLocalCtrlProgramByAddress(address string) (*CtrlProgram, error) {
528 program, err := m.getProgramByAddress(address)
534 sha3pool.Sum256(hash[:], program)
535 rawProgram := m.db.Get(ContractKey(hash))
536 if rawProgram == nil {
537 return nil, ErrFindCtrlProgram
541 return cp, json.Unmarshal(rawProgram, cp)
544 // GetMiningAddress will return the mining address
545 func (m *Manager) GetMiningAddress() (string, error) {
546 cp, err := m.GetCoinbaseCtrlProgram()
550 return cp.Address, nil
553 // IsLocalControlProgram check is the input control program belong to local
554 func (m *Manager) IsLocalControlProgram(prog []byte) bool {
556 sha3pool.Sum256(hash[:], prog)
557 bytes := m.db.Get(ContractKey(hash))
561 // ListAccounts will return the accounts in the db
562 func (m *Manager) ListAccounts(id string) ([]*Account, error) {
563 accounts := []*Account{}
564 accountIter := m.db.IteratorPrefix(Key(strings.TrimSpace(id)))
565 defer accountIter.Release()
567 for accountIter.Next() {
568 account := &Account{}
569 if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
572 accounts = append(accounts, account)
577 // ListControlProgram return all the local control program
578 func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
579 cps := []*CtrlProgram{}
580 cpIter := m.db.IteratorPrefix(contractPrefix)
581 defer cpIter.Release()
585 if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
588 cps = append(cps, cp)
593 func (m *Manager) ListUnconfirmedUtxo(accountID string, isSmartContract bool) []*UTXO {
594 utxos := m.utxoKeeper.ListUnconfirmed()
596 for _, utxo := range utxos {
597 if segwit.IsP2WScript(utxo.ControlProgram) != isSmartContract && (accountID == utxo.AccountID || accountID == "") {
598 result = append(result, utxo)
604 // RemoveUnconfirmedUtxo remove utxos from the utxoKeeper
605 func (m *Manager) RemoveUnconfirmedUtxo(hashes []*bc.Hash) {
606 m.utxoKeeper.RemoveUnconfirmedUtxo(hashes)
609 // SetMiningAddress will set the mining address
610 func (m *Manager) SetMiningAddress(miningAddress string) (string, error) {
611 program, err := m.getProgramByAddress(miningAddress)
617 Address: miningAddress,
618 ControlProgram: program,
620 rawCP, err := json.Marshal(cp)
625 m.db.Set(miningAddressKey, rawCP)
626 return m.GetMiningAddress()
629 func (m *Manager) SetCoinbaseArbitrary(arbitrary []byte) {
630 m.db.Set(CoinbaseAbKey, arbitrary)
633 // CreateCtrlProgram generate an address for the select account
634 func CreateCtrlProgram(account *Account, addrIdx uint64, change bool) (cp *CtrlProgram, err error) {
635 path, err := signers.Path(account.Signer, signers.AccountKeySpace, change, addrIdx)
640 if len(account.XPubs) == 1 {
641 cp, err = createP2PKH(account, path)
643 cp, err = createP2SH(account, path)
648 cp.KeyIndex, cp.Change = addrIdx, change
652 func createP2PKH(account *Account, path [][]byte) (*CtrlProgram, error) {
653 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
654 derivedPK := derivedXPubs[0].PublicKey()
655 pubHash := crypto.Ripemd160(derivedPK)
657 address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
662 control, err := vmutil.P2WPKHProgram([]byte(pubHash))
668 AccountID: account.ID,
669 Address: address.EncodeAddress(),
670 ControlProgram: control,
674 func createP2SH(account *Account, path [][]byte) (*CtrlProgram, error) {
675 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
676 derivedPKs := chainkd.XPubKeys(derivedXPubs)
677 signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
681 scriptHash := crypto.Sha256(signScript)
683 address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
688 control, err := vmutil.P2WSHProgram(scriptHash)
694 AccountID: account.ID,
695 Address: address.EncodeAddress(),
696 ControlProgram: control,
700 func GetAccountIndexKey(xpubs []chainkd.XPub) []byte {
703 cpy := append([]chainkd.XPub{}, xpubs[:]...)
704 sort.Sort(signers.SortKeys(cpy))
705 for _, xpub := range cpy {
706 xPubs = append(xPubs, xpub[:]...)
708 sha3pool.Sum256(hash[:], xPubs)
709 return append(accountIndexPrefix, hash[:]...)
712 func (m *Manager) getCurrentContractIndex(account *Account, change bool) (uint64, error) {
713 switch account.DeriveRule {
714 case signers.BIP0032:
715 return m.GetContractIndex(account.ID), nil
716 case signers.BIP0044:
717 return m.GetBip44ContractIndex(account.ID, change), nil
719 return 0, ErrDeriveRule
722 func (m *Manager) getProgramByAddress(address string) ([]byte, error) {
723 addr, err := common.DecodeAddress(address, &consensus.ActiveNetParams)
727 redeemContract := addr.ScriptAddress()
730 case *common.AddressWitnessPubKeyHash:
731 program, err = vmutil.P2WPKHProgram(redeemContract)
732 case *common.AddressWitnessScriptHash:
733 program, err = vmutil.P2WSHProgram(redeemContract)
735 return nil, ErrInvalidAddress
743 func (m *Manager) saveControlProgram(prog *CtrlProgram, updateIndex bool) error {
746 sha3pool.Sum256(hash[:], prog.ControlProgram)
747 acct, err := m.GetAccountByProgram(prog)
752 accountCP, err := json.Marshal(prog)
757 storeBatch := m.db.NewBatch()
758 storeBatch.Set(ContractKey(hash), accountCP)
760 switch acct.DeriveRule {
761 case signers.BIP0032:
762 storeBatch.Set(contractIndexKey(acct.ID), common.Unit64ToBytes(prog.KeyIndex))
763 case signers.BIP0044:
764 storeBatch.Set(bip44ContractIndexKey(acct.ID, prog.Change), common.Unit64ToBytes(prog.KeyIndex))
772 // SaveControlPrograms save account control programs
773 func (m *Manager) SaveControlPrograms(progs ...*CtrlProgram) error {
775 defer m.addressMu.Unlock()
777 for _, prog := range progs {
778 acct, err := m.GetAccountByProgram(prog)
783 currentIndex, err := m.getCurrentContractIndex(acct, prog.Change)
788 m.saveControlProgram(prog, prog.KeyIndex > currentIndex)