12 log "github.com/sirupsen/logrus"
14 dbm "github.com/bytom/bytom/database/leveldb"
15 "github.com/bytom/bytom/errors"
16 "github.com/bytom/bytom/protocol/bc"
19 const desireUtxoCount = 5
21 // pre-define error types
23 ErrInsufficient = errors.New("reservation found insufficient funds")
24 ErrImmature = errors.New("reservation found immature funds")
25 ErrReserved = errors.New("reservation found outputs already reserved")
26 ErrMatchUTXO = errors.New("can't find utxo with given hash")
27 ErrReservation = errors.New("couldn't find reservation")
30 // UTXO describes an individual account utxo.
42 ControlProgramIndex uint64
47 // reservation describes a reservation of a set of UTXOs
48 type reservation struct {
55 type utxoKeeper struct {
56 // `sync/atomic` expects the first word in an allocated struct to be 64-bit
57 // aligned on both ARM and x86-32. See https://goo.gl/zW7dgq for more details.
61 currentHeight func() uint64
63 unconfirmed map[bc.Hash]*UTXO
64 reserved map[bc.Hash]uint64
65 reservations map[uint64]*reservation
68 func newUtxoKeeper(f func() uint64, walletdb dbm.DB) *utxoKeeper {
72 unconfirmed: make(map[bc.Hash]*UTXO),
73 reserved: make(map[bc.Hash]uint64),
74 reservations: make(map[uint64]*reservation),
80 func (uk *utxoKeeper) AddUnconfirmedUtxo(utxos []*UTXO) {
84 for _, utxo := range utxos {
85 uk.unconfirmed[utxo.OutputID] = utxo
89 // Cancel canceling the reservation with the provided ID.
90 func (uk *utxoKeeper) Cancel(rid uint64) {
96 // ListUnconfirmed return all the unconfirmed utxos
97 func (uk *utxoKeeper) ListUnconfirmed() []*UTXO {
102 for _, utxo := range uk.unconfirmed {
103 utxos = append(utxos, utxo)
108 func (uk *utxoKeeper) RemoveUnconfirmedUtxo(hashes []*bc.Hash) {
110 defer uk.mtx.Unlock()
112 for _, hash := range hashes {
113 delete(uk.unconfirmed, *hash)
117 func (uk *utxoKeeper) Reserve(accountID string, assetID *bc.AssetID, amount uint64, useUnconfirmed bool, vote []byte, exp time.Time) (*reservation, error) {
119 defer uk.mtx.Unlock()
121 utxos, immatureAmount := uk.findUtxos(accountID, assetID, useUnconfirmed, vote)
122 optUtxos, optAmount, reservedAmount := uk.optUTXOs(utxos, amount)
123 if optAmount+reservedAmount+immatureAmount < amount {
124 return nil, ErrInsufficient
127 if optAmount+reservedAmount < amount {
128 return nil, ErrImmature
131 if optAmount < amount {
132 return nil, ErrReserved
135 result := &reservation{
136 id: atomic.AddUint64(&uk.nextIndex, 1),
138 change: optAmount - amount,
142 uk.reservations[result.id] = result
143 for _, u := range optUtxos {
144 uk.reserved[u.OutputID] = result.id
149 func (uk *utxoKeeper) ReserveParticular(outHash bc.Hash, useUnconfirmed bool, exp time.Time) (*reservation, error) {
151 defer uk.mtx.Unlock()
153 if _, ok := uk.reserved[outHash]; ok {
154 return nil, ErrReserved
157 u, err := uk.findUtxo(outHash, useUnconfirmed)
162 if u.ValidHeight > uk.currentHeight() {
163 return nil, ErrImmature
166 result := &reservation{
167 id: atomic.AddUint64(&uk.nextIndex, 1),
171 uk.reservations[result.id] = result
172 uk.reserved[u.OutputID] = result.id
176 func (uk *utxoKeeper) cancel(rid uint64) {
177 res, ok := uk.reservations[rid]
182 delete(uk.reservations, rid)
183 for _, utxo := range res.utxos {
184 delete(uk.reserved, utxo.OutputID)
188 func (uk *utxoKeeper) expireWorker() {
189 ticker := time.NewTicker(1000 * time.Millisecond)
192 for now := range ticker.C {
193 uk.expireReservation(now)
197 func (uk *utxoKeeper) expireReservation(t time.Time) {
199 defer uk.mtx.Unlock()
201 for rid, res := range uk.reservations {
202 if res.expiry.Before(t) {
208 func (uk *utxoKeeper) findUtxos(accountID string, assetID *bc.AssetID, useUnconfirmed bool, vote []byte) ([]*UTXO, uint64) {
209 immatureAmount := uint64(0)
210 currentHeight := uk.currentHeight()
212 appendUtxo := func(u *UTXO) {
213 if u.AccountID != accountID || u.AssetID != *assetID || !bytes.Equal(u.Vote, vote) {
216 if u.ValidHeight > currentHeight {
217 immatureAmount += u.Amount
219 utxos = append(utxos, u)
223 utxoIter := uk.db.IteratorPrefix([]byte(UTXOPreFix))
224 defer utxoIter.Release()
225 for utxoIter.Next() {
227 if err := json.Unmarshal(utxoIter.Value(), u); err != nil {
228 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("utxoKeeper findUtxos fail on unmarshal utxo")
234 return utxos, immatureAmount
237 for _, u := range uk.unconfirmed {
240 return utxos, immatureAmount
243 func (uk *utxoKeeper) findUtxo(outHash bc.Hash, useUnconfirmed bool) (*UTXO, error) {
244 if u, ok := uk.unconfirmed[outHash]; useUnconfirmed && ok {
249 if data := uk.db.Get(StandardUTXOKey(outHash)); data != nil {
250 return u, json.Unmarshal(data, u)
252 if data := uk.db.Get(ContractUTXOKey(outHash)); data != nil {
253 return u, json.Unmarshal(data, u)
255 return nil, ErrMatchUTXO
258 func (uk *utxoKeeper) optUTXOs(utxos []*UTXO, amount uint64) ([]*UTXO, uint64, uint64) {
259 //sort the utxo by amount, bigger amount in front
260 var optAmount, reservedAmount uint64
261 sort.Slice(utxos, func(i, j int) bool {
262 return utxos[i].Amount > utxos[j].Amount
265 //push all the available utxos into list
266 utxoList := list.New()
267 for _, u := range utxos {
268 if _, ok := uk.reserved[u.OutputID]; ok {
269 reservedAmount += u.Amount
275 optList := list.New()
276 for node := utxoList.Front(); node != nil; node = node.Next() {
277 //append utxo if we haven't reached the required amount
278 if optAmount < amount {
279 optList.PushBack(node.Value)
280 optAmount += node.Value.(*UTXO).Amount
284 largestNode := optList.Front()
285 replaceList := list.New()
286 replaceAmount := optAmount - largestNode.Value.(*UTXO).Amount
288 for ; node != nil && replaceList.Len() <= desireUtxoCount-optList.Len(); node = node.Next() {
289 replaceList.PushBack(node.Value)
290 if replaceAmount += node.Value.(*UTXO).Amount; replaceAmount >= amount {
291 optList.Remove(largestNode)
292 optList.PushBackList(replaceList)
293 optAmount = replaceAmount
298 //largestNode remaining the same means that there is nothing to be replaced
299 if largestNode == optList.Front() {
304 optUtxos := []*UTXO{}
305 for e := optList.Front(); e != nil; e = e.Next() {
306 optUtxos = append(optUtxos, e.Value.(*UTXO))
308 return optUtxos, optAmount, reservedAmount