9 acc "github.com/vapor/account"
10 "github.com/vapor/asset"
11 "github.com/vapor/blockchain/query"
12 "github.com/vapor/blockchain/signers"
13 "github.com/vapor/crypto/ed25519/chainkd"
14 "github.com/vapor/crypto/sha3pool"
15 dbm "github.com/vapor/database/leveldb"
16 "github.com/vapor/errors"
17 "github.com/vapor/protocol/bc"
21 utxoPrefix byte = iota //UTXOPrefix is StandardUTXOKey prefix
22 sutxoPrefix //SUTXOPrefix is ContractUTXOKey prefix
25 accountPrefix // AccountPrefix is account ID prefix
28 txPrefix //TxPrefix is wallet database transactions prefix
29 txIndexPrefix //TxIndexPrefix is wallet database tx index prefix
30 unconfirmedTxPrefix //UnconfirmedTxPrefix is txpool unconfirmed transactions prefix
31 globalTxIndexPrefix //GlobalTxIndexPrefix is wallet database global tx index prefix
40 UTXOPrefix = []byte{utxoPrefix, colon}
41 SUTXOPrefix = []byte{sutxoPrefix, colon}
42 // ContractPrefix = []byte{contractPrefix, contractPrefix, colon}
43 ContractPrefix = "Contract:"
44 ContractIndexPrefix = []byte{contractIndexPrefix, colon}
45 AccountPrefix = []byte{accountPrefix, colon} // AccountPrefix is account ID prefix
46 AccountAliasPrefix = []byte{accountAliasPrefix, colon}
47 AccountIndexPrefix = []byte{accountIndexPrefix, colon}
48 TxPrefix = []byte{txPrefix, colon} //TxPrefix is wallet database transactions prefix
49 TxIndexPrefix = []byte{txIndexPrefix, colon} //TxIndexPrefix is wallet database tx index prefix
50 UnconfirmedTxPrefix = []byte{unconfirmedTxPrefix, colon} //UnconfirmedTxPrefix is txpool unconfirmed transactions prefix
51 GlobalTxIndexPrefix = []byte{globalTxIndexPrefix, colon} //GlobalTxIndexPrefix is wallet database global tx index prefix
52 WalletKey = []byte{walletKey}
53 MiningAddressKey = []byte{miningAddressKey}
54 CoinbaseAbKey = []byte{coinbaseAbKey}
55 RecoveryKey = []byte{recoveryKey}
60 // ErrFindAccount = errors.New("Failed to find account")
61 errAccntTxIDNotFound = errors.New("account TXID not found")
62 errGetAsset = errors.New("Failed to find asset definition")
65 func accountIndexKey(xpubs []chainkd.XPub) []byte {
68 cpy := append([]chainkd.XPub{}, xpubs[:]...)
69 sort.Sort(signers.SortKeys(cpy))
70 for _, xpub := range cpy {
71 xPubs = append(xPubs, xpub[:]...)
73 sha3pool.Sum256(hash[:], xPubs)
74 return append([]byte(AccountIndexPrefix), hash[:]...)
77 func Bip44ContractIndexKey(accountID string, change bool) []byte {
78 key := append([]byte(ContractIndexPrefix), accountID...)
80 return append(key, []byte{1}...)
82 return append(key, []byte{0}...)
85 // ContractKey account control promgram store prefix
86 func ContractKey(hash bc.Hash) []byte {
88 // return append([]byte(ContractPrefix), []byte(h)...)
89 return append([]byte(ContractPrefix), hash.Bytes()...)
92 // AccountIDKey account id store prefix
93 func AccountIDKey(accountID string) []byte {
94 return append([]byte(AccountPrefix), []byte(accountID)...)
97 // StandardUTXOKey makes an account unspent outputs key to store
98 func StandardUTXOKey(id bc.Hash) []byte {
99 // name := id.String()
100 // return append(UTXOPrefix, []byte(name)...)
101 return append(UTXOPrefix, id.Bytes()...)
104 // ContractUTXOKey makes a smart contract unspent outputs key to store
105 func ContractUTXOKey(id bc.Hash) []byte {
106 // name := id.String()
107 // return append(SUTXOPrefix, []byte(name)...)
108 return append(SUTXOPrefix, id.Bytes()...)
111 func calcDeleteKey(blockHeight uint64) []byte {
112 return []byte(fmt.Sprintf("%s%016x", TxPrefix, blockHeight))
115 func calcTxIndexKey(txID string) []byte {
116 return append(TxIndexPrefix, []byte(txID)...)
119 func calcAnnotatedKey(formatKey string) []byte {
120 return append(TxPrefix, []byte(formatKey)...)
123 func calcUnconfirmedTxKey(formatKey string) []byte {
124 return append(UnconfirmedTxPrefix, []byte(formatKey)...)
127 func calcGlobalTxIndexKey(txID string) []byte {
128 return append(GlobalTxIndexPrefix, []byte(txID)...)
131 func CalcGlobalTxIndex(blockHash *bc.Hash, position uint64) []byte {
132 txIdx := make([]byte, 40)
133 copy(txIdx[:32], blockHash.Bytes())
134 binary.BigEndian.PutUint64(txIdx[32:], position)
138 func formatKey(blockHeight uint64, position uint32) string {
139 return fmt.Sprintf("%016x%08x", blockHeight, position)
142 func contractIndexKey(accountID string) []byte {
143 return append([]byte(ContractIndexPrefix), []byte(accountID)...)
146 func accountAliasKey(name string) []byte {
147 return append([]byte(AccountAliasPrefix), []byte(name)...)
150 // WalletStore store wallet using leveldb
151 type WalletStore struct {
156 // NewWalletStore create new WalletStore struct
157 func NewWalletStore(db dbm.DB) *WalletStore {
164 // InitBatch initial batch
165 func (store *WalletStore) InitBatch() error {
166 if store.batch != nil {
167 return errors.New("WalletStore initail fail, store batch is not nil.")
169 store.batch = store.walletDB.NewBatch()
173 // CommitBatch commit batch
174 func (store *WalletStore) CommitBatch() error {
175 if store.batch == nil {
176 return errors.New("WalletStore commit fail, store batch is nil.")
183 // DeleteContractUTXO delete contract utxo by outputID
184 func (store *WalletStore) DeleteContractUTXO(outputID bc.Hash) {
185 if store.batch == nil {
186 store.walletDB.Delete(ContractUTXOKey(outputID))
188 store.batch.Delete(ContractUTXOKey(outputID))
192 // DeleteRecoveryStatus delete recovery status
193 func (store *WalletStore) DeleteRecoveryStatus() {
194 if store.batch == nil {
195 store.walletDB.Delete(RecoveryKey)
197 store.batch.Delete(RecoveryKey)
201 // DeleteTransactions delete transactions when orphan block rollback
202 func (store *WalletStore) DeleteTransactions(height uint64) {
203 batch := store.walletDB.NewBatch()
204 if store.batch != nil {
207 txIter := store.walletDB.IteratorPrefix(calcDeleteKey(height))
208 defer txIter.Release()
210 tmpTx := query.AnnotatedTx{}
212 if err := json.Unmarshal(txIter.Value(), &tmpTx); err == nil {
213 batch.Delete(calcTxIndexKey(tmpTx.ID.String()))
215 batch.Delete(txIter.Key())
217 if store.batch == nil {
222 // DeleteUnconfirmedTransaction delete unconfirmed tx by txID
223 func (store *WalletStore) DeleteUnconfirmedTransaction(txID string) {
224 if store.batch == nil {
225 store.walletDB.Delete(calcUnconfirmedTxKey(txID))
227 store.batch.Delete(calcUnconfirmedTxKey(txID))
231 // DeleteWalletTransactions delete all txs in wallet
232 func (store *WalletStore) DeleteWalletTransactions() {
233 batch := store.walletDB.NewBatch()
234 if store.batch != nil {
237 txIter := store.walletDB.IteratorPrefix([]byte(TxPrefix))
238 defer txIter.Release()
241 batch.Delete(txIter.Key())
244 txIndexIter := store.walletDB.IteratorPrefix([]byte(TxIndexPrefix))
245 defer txIndexIter.Release()
247 for txIndexIter.Next() {
248 batch.Delete(txIndexIter.Key())
250 if store.batch == nil {
255 // DeleteWalletUTXOs delete all txs in wallet
256 func (store *WalletStore) DeleteWalletUTXOs() {
257 batch := store.walletDB.NewBatch()
258 if store.batch != nil {
261 ruIter := store.walletDB.IteratorPrefix([]byte(UTXOPrefix))
262 defer ruIter.Release()
264 batch.Delete(ruIter.Key())
267 suIter := store.walletDB.IteratorPrefix([]byte(SUTXOPrefix))
268 defer suIter.Release()
270 batch.Delete(suIter.Key())
272 if store.batch == nil {
277 // GetAsset get asset by assetID
278 func (store *WalletStore) GetAsset(assetID *bc.AssetID) (*asset.Asset, error) {
279 definitionByte := store.walletDB.Get(asset.ExtAssetKey(assetID))
280 if definitionByte == nil {
281 return nil, errGetAsset
283 definitionMap := make(map[string]interface{})
284 if err := json.Unmarshal(definitionByte, &definitionMap); err != nil {
287 alias := assetID.String()
288 externalAsset := &asset.Asset{
291 DefinitionMap: definitionMap,
292 RawDefinitionByte: definitionByte,
294 return externalAsset, nil
297 // GetControlProgram get raw program by hash
298 func (store *WalletStore) GetControlProgram(hash bc.Hash) (*acc.CtrlProgram, error) {
299 rawProgram := store.walletDB.Get(ContractKey(hash))
300 if rawProgram == nil {
301 return nil, acc.ErrFindCtrlProgram
303 accountCP := new(acc.CtrlProgram)
304 if err := json.Unmarshal(rawProgram, &accountCP); err != nil {
307 return accountCP, nil
310 // GetGlobalTransactionIndex get global tx by txID
311 func (store *WalletStore) GetGlobalTransactionIndex(txID string) []byte {
312 return store.walletDB.Get(calcGlobalTxIndexKey(txID))
315 // GetStandardUTXO get standard utxo by id
316 func (store *WalletStore) GetStandardUTXO(outid bc.Hash) (*acc.UTXO, error) {
317 rawUTXO := store.walletDB.Get(StandardUTXOKey(outid))
319 return nil, fmt.Errorf("failed get standard UTXO, outputID: %s ", outid.String())
321 UTXO := new(acc.UTXO)
322 if err := json.Unmarshal(rawUTXO, UTXO); err != nil {
328 // GetTransaction get tx by txid
329 func (store *WalletStore) GetTransaction(txID string) (*query.AnnotatedTx, error) {
330 formatKey := store.walletDB.Get(calcTxIndexKey(txID))
331 if formatKey == nil {
332 return nil, errAccntTxIDNotFound
334 rawTx := store.walletDB.Get(calcAnnotatedKey(string(formatKey)))
335 tx := new(query.AnnotatedTx)
336 if err := json.Unmarshal(rawTx, tx); err != nil {
342 // GetUnconfirmedTransaction get unconfirmed tx by txID
343 func (store *WalletStore) GetUnconfirmedTransaction(txID string) (*query.AnnotatedTx, error) {
344 rawUnconfirmedTx := store.walletDB.Get(calcUnconfirmedTxKey(txID))
345 if rawUnconfirmedTx == nil {
346 return nil, fmt.Errorf("failed get unconfirmed tx, txID: %s ", txID)
348 tx := new(query.AnnotatedTx)
349 if err := json.Unmarshal(rawUnconfirmedTx, tx); err != nil {
355 // GetRecoveryStatus delete recovery status
356 func (store *WalletStore) GetRecoveryStatus(recoveryKey []byte) []byte {
357 return store.walletDB.Get(recoveryKey)
360 // GetWalletInfo get wallet information
361 func (store *WalletStore) GetWalletInfo() []byte {
362 return store.walletDB.Get([]byte(WalletKey))
365 // ListAccountUTXOs get all account unspent outputs
366 func (store *WalletStore) ListAccountUTXOs(key string) ([]*acc.UTXO, error) {
367 fmt.Println("ListAccountUTXOs []byte(key):", []byte(key))
368 accountUtxoIter := store.walletDB.IteratorPrefix([]byte(key))
369 defer accountUtxoIter.Release()
371 confirmedUTXOs := []*acc.UTXO{}
372 for accountUtxoIter.Next() {
373 utxo := new(acc.UTXO)
374 if err := json.Unmarshal(accountUtxoIter.Value(), utxo); err != nil {
377 confirmedUTXOs = append(confirmedUTXOs, utxo)
379 return confirmedUTXOs, nil
382 func (store *WalletStore) ListTransactions(accountID string, StartTxID string, count uint, unconfirmed bool) ([]*query.AnnotatedTx, error) {
383 annotatedTxs := []*query.AnnotatedTx{}
389 startKey = calcUnconfirmedTxKey(StartTxID)
391 formatKey := store.walletDB.Get(calcTxIndexKey(StartTxID))
392 if formatKey == nil {
393 return nil, errAccntTxIDNotFound
395 startKey = calcAnnotatedKey(string(formatKey))
400 preFix = UnconfirmedTxPrefix
403 itr := store.walletDB.IteratorPrefixWithStart([]byte(preFix), startKey, true)
406 for txNum := count; itr.Next() && txNum > 0; txNum-- {
407 annotatedTx := new(query.AnnotatedTx)
408 if err := json.Unmarshal(itr.Value(), &annotatedTx); err != nil {
411 annotatedTxs = append(annotatedTxs, annotatedTx)
414 return annotatedTxs, nil
417 // ListUnconfirmedTransactions get all unconfirmed txs
418 func (store *WalletStore) ListUnconfirmedTransactions() ([]*query.AnnotatedTx, error) {
419 annotatedTxs := []*query.AnnotatedTx{}
420 txIter := store.walletDB.IteratorPrefix([]byte(UnconfirmedTxPrefix))
421 defer txIter.Release()
424 annotatedTx := &query.AnnotatedTx{}
425 if err := json.Unmarshal(txIter.Value(), &annotatedTx); err != nil {
428 annotatedTxs = append(annotatedTxs, annotatedTx)
430 return annotatedTxs, nil
433 // SetAssetDefinition set assetID and definition
434 func (store *WalletStore) SetAssetDefinition(assetID *bc.AssetID, definition []byte) {
435 if store.batch == nil {
436 store.walletDB.Set(asset.ExtAssetKey(assetID), definition)
438 store.batch.Set(asset.ExtAssetKey(assetID), definition)
442 // SetContractUTXO set standard utxo
443 func (store *WalletStore) SetContractUTXO(outputID bc.Hash, utxo *acc.UTXO) error {
444 data, err := json.Marshal(utxo)
448 if store.batch == nil {
449 store.walletDB.Set(ContractUTXOKey(outputID), data)
451 store.batch.Set(ContractUTXOKey(outputID), data)
456 // SetGlobalTransactionIndex set global tx index by blockhash and position
457 func (store *WalletStore) SetGlobalTransactionIndex(globalTxID string, blockHash *bc.Hash, position uint64) {
458 if store.batch == nil {
459 store.walletDB.Set(calcGlobalTxIndexKey(globalTxID), CalcGlobalTxIndex(blockHash, position))
461 store.batch.Set(calcGlobalTxIndexKey(globalTxID), CalcGlobalTxIndex(blockHash, position))
465 // SetRecoveryStatus set recovery status
466 func (store *WalletStore) SetRecoveryStatus(recoveryKey, rawStatus []byte) {
467 if store.batch == nil {
468 store.walletDB.Set(recoveryKey, rawStatus)
470 store.batch.Set(recoveryKey, rawStatus)
474 // SetTransaction set raw transaction by block height and tx position
475 func (store *WalletStore) SetTransaction(height uint64, tx *query.AnnotatedTx) error {
476 batch := store.walletDB.NewBatch()
477 if store.batch != nil {
481 rawTx, err := json.Marshal(tx)
485 batch.Set(calcAnnotatedKey(formatKey(height, tx.Position)), rawTx)
486 batch.Set(calcTxIndexKey(tx.ID.String()), []byte(formatKey(height, tx.Position)))
488 if store.batch == nil {
494 // SetUnconfirmedTransaction set unconfirmed tx by txID
495 func (store *WalletStore) SetUnconfirmedTransaction(txID string, tx *query.AnnotatedTx) error {
496 rawTx, err := json.Marshal(tx)
500 if store.batch == nil {
501 store.walletDB.Set(calcUnconfirmedTxKey(txID), rawTx)
503 store.batch.Set(calcUnconfirmedTxKey(txID), rawTx)
508 // SetWalletInfo get wallet information
509 func (store *WalletStore) SetWalletInfo(rawWallet []byte) {
510 if store.batch == nil {
511 store.walletDB.Set([]byte(WalletKey), rawWallet)
513 store.batch.Set([]byte(WalletKey), rawWallet)