6 log "github.com/sirupsen/logrus"
8 "github.com/bytom/vapor/account"
9 "github.com/bytom/vapor/asset"
10 "github.com/bytom/vapor/blockchain/pseudohsm"
11 "github.com/bytom/vapor/errors"
12 "github.com/bytom/vapor/event"
13 "github.com/bytom/vapor/protocol"
14 "github.com/bytom/vapor/protocol/bc"
15 "github.com/bytom/vapor/protocol/bc/types"
25 currentVersion = uint(1)
27 errBestBlockNotFoundInCore = errors.New("best block not found in core")
28 errWalletVersionMismatch = errors.New("wallet version mismatch")
29 ErrGetWalletStatusInfo = errors.New("failed get wallet info")
30 ErrGetAsset = errors.New("Failed to find asset definition")
31 ErrAccntTxIDNotFound = errors.New("account TXID not found")
32 ErrGetStandardUTXO = errors.New("failed get standard UTXO")
35 //StatusInfo is base valid block info to handle orphan block rollback
36 type StatusInfo struct {
44 //Wallet is related to storing account unspent outputs
50 AccountMgr *account.Manager
51 AssetReg *asset.Registry
54 RecoveryMgr *recoveryManager
55 EventDispatcher *event.Dispatcher
56 TxMsgSub *event.Subscription
58 rescanCh chan struct{}
61 //NewWallet return a new wallet instance
62 func NewWallet(store WalletStore, account *account.Manager, asset *asset.Registry, hsm *pseudohsm.HSM, chain *protocol.Chain, dispatcher *event.Dispatcher, txIndexFlag bool) (*Wallet, error) {
69 RecoveryMgr: NewRecoveryManager(store, account),
70 EventDispatcher: dispatcher,
71 rescanCh: make(chan struct{}, 1),
72 TxIndexFlag: txIndexFlag,
75 if err := w.LoadWalletInfo(); err != nil {
79 if err := w.RecoveryMgr.LoadStatusInfo(); err != nil {
84 w.TxMsgSub, err = w.EventDispatcher.Subscribe(protocol.TxMsgEvent{})
90 go w.delUnconfirmedTx()
91 go w.MemPoolTxQueryLoop()
95 // MemPoolTxQueryLoop constantly pass a transaction accepted by mempool to the wallet.
96 func (w *Wallet) MemPoolTxQueryLoop() {
99 case obj, ok := <-w.TxMsgSub.Chan():
101 log.WithFields(log.Fields{"module": logModule}).Warning("tx pool tx msg subscription channel closed")
105 ev, ok := obj.Data.(protocol.TxMsgEvent)
107 log.WithFields(log.Fields{"module": logModule}).Error("event type error")
111 switch ev.TxMsg.MsgType {
112 case protocol.MsgNewTx:
113 w.AddUnconfirmedTx(ev.TxMsg.TxDesc)
114 case protocol.MsgRemoveTx:
115 w.RemoveUnconfirmedTx(ev.TxMsg.TxDesc)
117 log.WithFields(log.Fields{"module": logModule}).Warn("got unknow message type from the txPool channel")
123 func (w *Wallet) checkWalletInfo() error {
124 if w.Status.Version != currentVersion {
125 return errWalletVersionMismatch
126 } else if !w.Chain.BlockExist(&w.Status.BestHash) {
127 return errBestBlockNotFoundInCore
133 //LoadWalletInfo return stored wallet info and nil,
134 //if error, return initial wallet info and err
135 func (w *Wallet) LoadWalletInfo() error {
136 walletStatus, err := w.Store.GetWalletInfo()
137 if walletStatus == nil && err != ErrGetWalletStatusInfo {
141 if walletStatus != nil {
142 w.Status = *walletStatus
143 err = w.checkWalletInfo()
148 log.WithFields(log.Fields{"module": logModule}).Warn(err.Error())
149 w.Store.DeleteWalletTransactions()
150 w.Store.DeleteWalletUTXOs()
153 w.Status.Version = currentVersion
154 w.Status.WorkHash = bc.Hash{}
155 block, err := w.Chain.GetBlockByHeight(0)
160 return w.AttachBlock(block)
163 func (w *Wallet) commitWalletInfo(store WalletStore) error {
164 if err := store.SetWalletInfo(&w.Status); err != nil {
165 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("save wallet info")
171 // AttachBlock attach a new block
172 func (w *Wallet) AttachBlock(block *types.Block) error {
176 if block.PreviousBlockHash != w.Status.WorkHash {
177 log.Warn("wallet skip attachBlock due to status hash not equal to previous hash")
181 blockHash := block.Hash()
182 txStatus, err := w.Chain.GetTransactionStatus(&blockHash)
187 if err := w.RecoveryMgr.FilterRecoveryTxs(block); err != nil {
188 log.WithField("err", err).Error("filter recovery txs")
189 w.RecoveryMgr.finished()
192 annotatedTxs := w.filterAccountTxs(block, txStatus)
193 if err := saveExternalAssetDefinition(block, w.Store); err != nil {
197 w.annotateTxsAccount(annotatedTxs)
199 newStore := w.Store.InitBatch()
200 if err := w.indexTransactions(block, txStatus, annotatedTxs, newStore); err != nil {
204 w.attachUtxos(block, txStatus, newStore)
205 w.Status.WorkHeight = block.Height
206 w.Status.WorkHash = block.Hash()
207 if w.Status.WorkHeight >= w.Status.BestHeight {
208 w.Status.BestHeight = w.Status.WorkHeight
209 w.Status.BestHash = w.Status.WorkHash
212 if err := w.commitWalletInfo(newStore); err != nil {
216 if err := newStore.CommitBatch(); err != nil {
223 // DetachBlock detach a block and rollback state
224 func (w *Wallet) DetachBlock(block *types.Block) error {
228 blockHash := block.Hash()
229 txStatus, err := w.Chain.GetTransactionStatus(&blockHash)
234 newStore := w.Store.InitBatch()
236 w.detachUtxos(block, txStatus, newStore)
237 newStore.DeleteTransactions(w.Status.BestHeight)
239 w.Status.BestHeight = block.Height - 1
240 w.Status.BestHash = block.PreviousBlockHash
242 if w.Status.WorkHeight > w.Status.BestHeight {
243 w.Status.WorkHeight = w.Status.BestHeight
244 w.Status.WorkHash = w.Status.BestHash
246 if err := w.commitWalletInfo(newStore); err != nil {
250 if err := newStore.CommitBatch(); err != nil {
257 //WalletUpdate process every valid block and reverse every invalid block which need to rollback
258 func (w *Wallet) walletUpdater() {
260 w.getRescanNotification()
261 for !w.Chain.InMainChain(w.Status.BestHash) {
262 block, err := w.Chain.GetBlockByHash(&w.Status.BestHash)
264 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("walletUpdater GetBlockByHash")
268 if err := w.DetachBlock(block); err != nil {
269 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("walletUpdater detachBlock stop")
274 block, _ := w.Chain.GetBlockByHeight(w.Status.WorkHeight + 1)
276 w.walletBlockWaiter()
280 if err := w.AttachBlock(block); err != nil {
281 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("walletUpdater AttachBlock stop")
287 //RescanBlocks provide a trigger to rescan blocks
288 func (w *Wallet) RescanBlocks() {
290 case w.rescanCh <- struct{}{}:
296 // DeleteAccount deletes account matching accountID, then rescan wallet
297 func (w *Wallet) DeleteAccount(accountID string) (err error) {
301 if err := w.AccountMgr.DeleteAccount(accountID); err != nil {
305 w.Store.DeleteWalletTransactions()
310 func (w *Wallet) UpdateAccountAlias(accountID string, newAlias string) (err error) {
314 if err := w.AccountMgr.UpdateAccountAlias(accountID, newAlias); err != nil {
318 w.Store.DeleteWalletTransactions()
323 func (w *Wallet) getRescanNotification() {
332 func (w *Wallet) setRescanStatus() {
333 block, _ := w.Chain.GetBlockByHeight(0)
334 w.Status.WorkHash = bc.Hash{}
338 func (w *Wallet) walletBlockWaiter() {
340 case <-w.Chain.BlockWaiter(w.Status.WorkHeight + 1):
346 // GetWalletStatusInfo return current wallet StatusInfo
347 func (w *Wallet) GetWalletStatusInfo() StatusInfo {