11 "github.com/vapor/account"
12 "github.com/vapor/blockchain/signers"
13 "github.com/vapor/crypto/ed25519/chainkd"
14 "github.com/vapor/crypto/sha3pool"
15 "github.com/vapor/errors"
16 "github.com/vapor/protocol/bc"
17 "github.com/vapor/protocol/bc/types"
21 // acctRecoveryWindow defines the account derivation lookahead used when
22 // attempting to recover the set of used accounts.
23 acctRecoveryWindow = uint64(6)
25 // addrRecoveryWindow defines the address derivation lookahead used when
26 // attempting to recover the set of used addresses.
27 addrRecoveryWindow = uint64(128)
30 //recoveryKey key for db store recovery info.
32 recoveryKey = []byte("RecoveryInfo")
34 // ErrRecoveryBusy another recovery in progress, can not get recovery manager lock
35 ErrRecoveryBusy = errors.New("another recovery in progress")
37 // ErrInvalidAcctID can not find account by account id
38 ErrInvalidAcctID = errors.New("invalid account id")
41 // branchRecoveryState maintains the required state in-order to properly
42 // recover addresses derived from a particular account's internal or external
45 // A branch recovery state supports operations for:
46 // - Expanding the look-ahead horizon based on which indexes have been found.
47 // - Registering derived addresses with indexes within the horizon.
48 // - Reporting an invalid child index that falls into the horizon.
49 // - Reporting that an address has been found.
50 // - Retrieving all currently derived addresses for the branch.
51 // - Looking up a particular address by its child index.
52 type branchRecoveryState struct {
53 // recoveryWindow defines the key-derivation lookahead used when
54 // attempting to recover the set of addresses on this branch.
57 // horizion records the highest child index watched by this branch.
60 // nextUnfound maintains the child index of the successor to the highest
61 // index that has been found during recovery of this branch.
65 // newBranchRecoveryState creates a new branchRecoveryState that can be used to
66 // track either the external or internal branch of an account's derivation path.
67 func newBranchRecoveryState(recoveryWindow uint64) *branchRecoveryState {
68 return &branchRecoveryState{
69 RecoveryWindow: recoveryWindow,
75 // extendHorizon returns the current horizon and the number of addresses that
76 // must be derived in order to maintain the desired recovery window.
77 func (brs *branchRecoveryState) extendHorizon() (uint64, uint64) {
78 // Compute the new horizon, which should surpass our last found address
79 // by the recovery window.
80 curHorizon := brs.Horizon
82 minValidHorizon := brs.NextUnfound + brs.RecoveryWindow
84 // If the current horizon is sufficient, we will not have to derive any
86 if curHorizon >= minValidHorizon {
90 // Otherwise, the number of addresses we should derive corresponds to
91 // the delta of the two horizons, and we update our new horizon.
92 delta := minValidHorizon - curHorizon
93 brs.Horizon = minValidHorizon
95 return curHorizon, delta
98 // reportFound updates the last found index if the reported index exceeds the
100 func (brs *branchRecoveryState) reportFound(index uint64) {
101 if index >= brs.NextUnfound {
102 brs.NextUnfound = index + 1
106 // addressRecoveryState is used to manage the recovery of addresses generated
107 // under a particular BIP32/BIP44 account. Each account tracks both an external and
108 // internal branch recovery state, both of which use the same recovery window.
109 type addressRecoveryState struct {
110 // ExternalBranch is the recovery state of addresses generated for
111 // external use, i.e. receiving addresses.
112 ExternalBranch *branchRecoveryState
114 // InternalBranch is the recovery state of addresses generated for
115 // internal use, i.e. change addresses.
116 InternalBranch *branchRecoveryState
118 Account *account.Account
121 func newAddressRecoveryState(recoveryWindow uint64, account *account.Account) *addressRecoveryState {
122 return &addressRecoveryState{
123 ExternalBranch: newBranchRecoveryState(recoveryWindow),
124 InternalBranch: newBranchRecoveryState(recoveryWindow),
129 // recoveryState used to record the status of a recovery process.
130 type recoveryState struct {
131 // XPubs recovery account xPubs
134 // The time to start the recovery task, used to detemine whether
135 // recovery task is completed.
138 // XPubsStatus maintains a map of each requested XPub to its active
139 // account recovery state.
140 XPubsStatus *branchRecoveryState
142 // AcctStatus maintains a map of each requested key scope to its active
144 AccountsStatus map[string]*addressRecoveryState
147 func newRecoveryState() *recoveryState {
148 return &recoveryState{
149 AccountsStatus: make(map[string]*addressRecoveryState),
150 StartTime: time.Now(),
154 // stateForScope returns a ScopeRecoveryState for the provided key scope. If one
155 // does not already exist, a new one will be generated with the RecoveryState's
157 func (rs *recoveryState) stateForScope(account *account.Account) {
158 // If the account recovery state already exists, return it.
159 if _, ok := rs.AccountsStatus[account.ID]; ok {
163 // Otherwise, initialize the recovery state for this scope with the
164 // chosen recovery window.
165 rs.AccountsStatus[account.ID] = newAddressRecoveryState(addrRecoveryWindow, account)
168 // recoveryManager manage recovery wallet from key.
169 type recoveryManager struct {
173 accountMgr *account.Manager
179 // state encapsulates and allocates the necessary recovery state for all
180 // key scopes and subsidiary derivation paths.
183 //addresses all addresses derivation lookahead used when
184 // attempting to recover the set of used addresses.
185 addresses map[bc.Hash]*account.CtrlProgram
188 // newRecoveryManager create recovery manger.
189 func newRecoveryManager(store WalletStore, accountMgr *account.Manager) *recoveryManager {
190 return &recoveryManager{
192 accountMgr: accountMgr,
193 addresses: make(map[bc.Hash]*account.CtrlProgram),
194 state: newRecoveryState(),
198 func (m *recoveryManager) AddrResurrect(accts []*account.Account) error {
202 for _, acct := range accts {
203 m.state.stateForScope(acct)
204 if err := m.extendScanAddresses(acct.ID, false); err != nil {
208 //Bip32 path no change field, no need to create addresses repeatedly.
209 if acct.DeriveRule == signers.BIP0032 {
212 if err := m.extendScanAddresses(acct.ID, true); err != nil {
217 m.state.StartTime = time.Now()
218 if err := m.commitStatusInfo(); err != nil {
226 func (m *recoveryManager) AcctResurrect(xPubs []chainkd.XPub) error {
230 if !m.tryStartXPubsRec() {
231 return ErrRecoveryBusy
234 m.state.XPubs = xPubs
235 m.state.XPubsStatus = newBranchRecoveryState(acctRecoveryWindow)
237 if err := m.extendScanAccounts(); err != nil {
241 m.state.StartTime = time.Now()
242 if err := m.commitStatusInfo(); err != nil {
250 func (m *recoveryManager) commitStatusInfo() error {
251 rawStatus, err := json.Marshal(m.state)
256 m.store.SetRecoveryStatus(recoveryKey, rawStatus)
260 func genAcctAlias(xPubs []chainkd.XPub, index uint64) string {
262 for _, xPub := range xPubs {
263 tmp = append(tmp, xPub[:6]...)
265 return fmt.Sprintf("%x:%x", tmp, index)
268 func (m *recoveryManager) extendScanAccounts() error {
269 if m.state.XPubsStatus == nil {
273 curHorizon, delta := m.state.XPubsStatus.extendHorizon()
274 for index := curHorizon; index < curHorizon+delta; index++ {
275 alias := genAcctAlias(m.state.XPubs, index)
276 account, err := account.CreateAccount(m.state.XPubs, len(m.state.XPubs), alias, index, signers.BIP0044)
281 m.state.stateForScope(account)
282 //generate resurrect address for new account.
283 if err := m.extendScanAddresses(account.ID, true); err != nil {
287 if err := m.extendScanAddresses(account.ID, false); err != nil {
295 func getCPHash(cp []byte) bc.Hash {
297 sha3pool.Sum256(h[:], cp)
301 func (m *recoveryManager) extendAddress(acct *account.Account, index uint64, change bool) error {
302 cp, err := account.CreateCtrlProgram(acct, index, change)
307 m.addresses[getCPHash(cp.ControlProgram)] = cp
311 func (m *recoveryManager) extendScanAddresses(accountID string, change bool) error {
312 state, ok := m.state.AccountsStatus[accountID]
314 return ErrInvalidAcctID
317 var curHorizon, delta uint64
319 curHorizon, delta = state.InternalBranch.extendHorizon()
321 curHorizon, delta = state.ExternalBranch.extendHorizon()
323 for index := curHorizon; index < curHorizon+delta; index++ {
324 if err := m.extendAddress(state.Account, index, change); err != nil {
331 func (m *recoveryManager) processBlock(b *types.Block) error {
332 for _, tx := range b.Transactions {
333 for _, output := range tx.Outputs {
334 if cp, ok := m.addresses[getCPHash(output.ControlProgram())]; ok {
335 status, ok := m.state.AccountsStatus[cp.AccountID]
337 return ErrInvalidAcctID
340 if err := m.reportFound(status.Account, cp); err != nil {
350 // FilterRecoveryTxs Filter transactions that meet the recovery address
351 func (m *recoveryManager) FilterRecoveryTxs(b *types.Block) error {
358 if b.Time().After(m.state.StartTime) {
362 return m.processBlock(b)
365 func (m *recoveryManager) finished() {
366 m.store.DeleteRecoveryStatus()
368 m.addresses = make(map[bc.Hash]*account.CtrlProgram)
369 m.state = newRecoveryState()
373 func (m *recoveryManager) LoadStatusInfo() error {
377 rawStatus := m.store.GetRecoveryStatus(recoveryKey)
378 if rawStatus == nil {
382 if err := json.Unmarshal(rawStatus, m.state); err != nil {
386 if m.state.XPubs != nil && !m.tryStartXPubsRec() {
387 return ErrRecoveryBusy
390 if err := m.restoreAddresses(); err != nil {
399 // restoreAddresses resume addresses for unfinished tasks
400 func (m *recoveryManager) restoreAddresses() error {
401 for _, state := range m.state.AccountsStatus {
402 for index := uint64(1); index <= state.InternalBranch.Horizon; index++ {
403 if err := m.extendAddress(state.Account, index, true); err != nil {
408 for index := uint64(1); index <= state.ExternalBranch.Horizon; index++ {
409 if err := m.extendAddress(state.Account, index, false); err != nil {
417 // reportFound found your own address operation.
418 func (m *recoveryManager) reportFound(account *account.Account, cp *account.CtrlProgram) error {
419 if m.state.XPubsStatus != nil && reflect.DeepEqual(m.state.XPubs, account.XPubs) {
420 //recovery from XPubs need save account to db.
421 if err := m.saveAccount(account); err != nil {
425 m.state.XPubsStatus.reportFound(account.KeyIndex)
426 if err := m.extendScanAccounts(); err != nil {
432 m.state.AccountsStatus[account.ID].InternalBranch.reportFound(cp.KeyIndex)
434 m.state.AccountsStatus[account.ID].ExternalBranch.reportFound(cp.KeyIndex)
437 if err := m.extendScanAddresses(account.ID, cp.Change); err != nil {
441 if err := m.accountMgr.CreateBatchAddresses(account.ID, cp.Change, cp.KeyIndex); err != nil {
445 return m.commitStatusInfo()
448 func (m *recoveryManager) saveAccount(acct *account.Account) error {
449 tmp, err := m.accountMgr.FindByID(acct.ID)
450 if err != nil && errors.Root(err) != account.ErrFindAccount {
457 return m.accountMgr.SaveAccount(acct)
460 //tryStartXPubsRec guarantee that only one xPubs recovery is in progress.
461 func (m *recoveryManager) tryStartXPubsRec() bool {
462 return atomic.CompareAndSwapInt32(&m.locked, 0, 1)
465 //stopXPubsRec release xPubs recovery lock.
466 func (m *recoveryManager) stopXPubsRec() {
468 atomic.StoreInt32(&m.locked, 0)