Skip to content

Commit

Permalink
Check consistency of account id, name index on open
Browse files Browse the repository at this point in the history
  • Loading branch information
tuxcanfly committed May 4, 2015
1 parent c820c8a commit c02bf11
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions waddrmgr/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -1746,6 +1746,11 @@ func upgradeManager(namespace walletdb.Namespace, pubPassPhrase []byte, chainPar
version = 4
}

// Ensure that the account indexes are up-to-date and consistent
if err := updateAccountIndexes(namespace); err != nil {
return err
}

// Ensure the manager is upraded to the latest version. This check is
// to intentionally cause a failure if the manager version is updated
// without writing code to handle the upgrade.
Expand Down Expand Up @@ -1970,3 +1975,58 @@ func upgradeToVersion4(namespace walletdb.Namespace, pubPassPhrase []byte) error
}
return nil
}

// updateAccountIndexes checks for any missing entries in the account id
// and name indexes and rebuils them, if required, to make sure that the
// indexes are consistent
func updateAccountIndexes(namespace walletdb.Namespace) error {
err := namespace.Update(func(tx walletdb.Tx) error {
bucket := tx.RootBucket().Bucket(acctBucketName)

err := bucket.ForEach(func(k, v []byte) error {
// Skip buckets.
if v == nil {
return nil
}

// Fetch the name from the account row
account := binary.LittleEndian.Uint32(k)
acctInfoIface, err := fetchAccountInfo(tx, account)
if err != nil {
return err
}
acctInfo, ok := acctInfoIface.(*dbBIP0044AccountRow)
if !ok {
str := fmt.Sprintf("unsupported account type %T", acctInfoIface)
return managerError(ErrDatabase, str, nil)
}
name := acctInfo.name

// Check that the bidirectional index exists for this (id, name)
// pair and rebuild entries if required
oldName, _ := fetchAccountName(tx, account)
if oldName != name {
if err := putAccountIDIndex(tx, account, name); err != nil {
return err
}
fmt.Printf("account #%d: fixed invalid id index - "+
"'%s' -> '%s'\n", account, oldName, name)
}

oldAccount, _ := fetchAccountByName(tx, name)
if oldAccount != account {
if err := putAccountNameIndex(tx, account, name); err != nil {
return err
}
fmt.Printf("account '%s': fixed invalid name index - "+
"#%d -> #%d\n", name, oldAccount, account)
}
return nil
})
return err
})
if err != nil {
return maybeConvertDbError(err)
}
return nil
}

0 comments on commit c02bf11

Please sign in to comment.