all: fix inconsistent receiver name (#1494)

Co-authored-by: wit <wit765765346@gmail>
This commit is contained in:
wit liu 2025-09-17 08:15:23 +08:00 committed by GitHub
parent c9f2b73861
commit a5d03e4a8a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 566 additions and 566 deletions

View file

@ -564,8 +564,8 @@ func (XDCx *XDCX) GetTradingState(block *types.Block, author common.Address) (*t
} }
return tradingstate.New(root, XDCx.StateCache) return tradingstate.New(root, XDCx.StateCache)
} }
func (XDCX *XDCX) GetEmptyTradingState() (*tradingstate.TradingStateDB, error) { func (XDCx *XDCX) GetEmptyTradingState() (*tradingstate.TradingStateDB, error) {
return tradingstate.New(tradingstate.EmptyRoot, XDCX.StateCache) return tradingstate.New(tradingstate.EmptyRoot, XDCx.StateCache)
} }
func (XDCx *XDCX) GetStateCache() tradingstate.Database { func (XDCx *XDCX) GetStateCache() tradingstate.Database {

View file

@ -306,26 +306,26 @@ func (s *stateLendingBook) DumpOrderList(db Database) DumpOrderList {
return mapResult return mapResult
} }
func (l *liquidationPriceState) DumpLendingBook(db Database) (DumpLendingBook, error) { func (s *liquidationPriceState) DumpLendingBook(db Database) (DumpLendingBook, error) {
result := DumpLendingBook{Volume: l.Volume(), LendingBooks: map[common.Hash]DumpOrderList{}} result := DumpLendingBook{Volume: s.Volume(), LendingBooks: map[common.Hash]DumpOrderList{}}
it := trie.NewIterator(l.getTrie(db).NodeIterator(nil)) it := trie.NewIterator(s.getTrie(db).NodeIterator(nil))
for it.Next() { for it.Next() {
lendingBook := common.BytesToHash(it.Key) lendingBook := common.BytesToHash(it.Key)
if lendingBook.IsZero() { if lendingBook.IsZero() {
continue continue
} }
if _, exist := l.stateLendingBooks[lendingBook]; exist { if _, exist := s.stateLendingBooks[lendingBook]; exist {
continue continue
} else { } else {
var data orderList var data orderList
if err := rlp.DecodeBytes(it.Value, &data); err != nil { if err := rlp.DecodeBytes(it.Value, &data); err != nil {
return result, fmt.Errorf("failed to decode state lending book orderbook: %s, liquidation price: %s , lendingBook: %s , err: %v", l.orderBook, l.liquidationPrice, lendingBook, err) return result, fmt.Errorf("failed to decode state lending book orderbook: %s, liquidation price: %s , lendingBook: %s , err: %v", s.orderBook, s.liquidationPrice, lendingBook, err)
} }
stateLendingBook := newStateLendingBook(l.orderBook, l.liquidationPrice, lendingBook, data, nil) stateLendingBook := newStateLendingBook(s.orderBook, s.liquidationPrice, lendingBook, data, nil)
result.LendingBooks[lendingBook] = stateLendingBook.DumpOrderList(db) result.LendingBooks[lendingBook] = stateLendingBook.DumpOrderList(db)
} }
} }
for lendingBook, stateLendingBook := range l.stateLendingBooks { for lendingBook, stateLendingBook := range s.stateLendingBooks {
if !lendingBook.IsZero() { if !lendingBook.IsZero() {
result.LendingBooks[lendingBook] = stateLendingBook.DumpOrderList(db) result.LendingBooks[lendingBook] = stateLendingBook.DumpOrderList(db)
} }

View file

@ -69,54 +69,54 @@ func newLiquidationPriceState(db *TradingStateDB, orderBook common.Hash, price c
} }
// EncodeRLP implements rlp.Encoder. // EncodeRLP implements rlp.Encoder.
func (l *liquidationPriceState) EncodeRLP(w io.Writer) error { func (s *liquidationPriceState) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, l.data) return rlp.Encode(w, s.data)
} }
// setError remembers the first non-nil error it is called with. // setError remembers the first non-nil error it is called with.
func (l *liquidationPriceState) setError(err error) { func (s *liquidationPriceState) setError(err error) {
if l.dbErr == nil { if s.dbErr == nil {
l.dbErr = err s.dbErr = err
} }
} }
func (l *liquidationPriceState) MarkStateLendingBookDirty(price common.Hash) { func (s *liquidationPriceState) MarkStateLendingBookDirty(price common.Hash) {
l.stateLendingBooksDirty[price] = struct{}{} s.stateLendingBooksDirty[price] = struct{}{}
if l.onDirty != nil { if s.onDirty != nil {
l.onDirty(l.liquidationPrice) s.onDirty(s.liquidationPrice)
l.onDirty = nil s.onDirty = nil
} }
} }
func (l *liquidationPriceState) createLendingBook(db Database, lendingBook common.Hash) (newobj *stateLendingBook) { func (s *liquidationPriceState) createLendingBook(db Database, lendingBook common.Hash) (newobj *stateLendingBook) {
newobj = newStateLendingBook(l.orderBook, l.liquidationPrice, lendingBook, orderList{Volume: Zero}, l.MarkStateLendingBookDirty) newobj = newStateLendingBook(s.orderBook, s.liquidationPrice, lendingBook, orderList{Volume: Zero}, s.MarkStateLendingBookDirty)
l.stateLendingBooks[lendingBook] = newobj s.stateLendingBooks[lendingBook] = newobj
l.stateLendingBooksDirty[lendingBook] = struct{}{} s.stateLendingBooksDirty[lendingBook] = struct{}{}
if l.onDirty != nil { if s.onDirty != nil {
l.onDirty(l.liquidationPrice) s.onDirty(s.liquidationPrice)
l.onDirty = nil s.onDirty = nil
} }
return newobj return newobj
} }
func (l *liquidationPriceState) getTrie(db Database) Trie { func (s *liquidationPriceState) getTrie(db Database) Trie {
if l.trie == nil { if s.trie == nil {
var err error var err error
l.trie, err = db.OpenStorageTrie(l.liquidationPrice, l.data.Root) s.trie, err = db.OpenStorageTrie(s.liquidationPrice, s.data.Root)
if err != nil { if err != nil {
l.trie, _ = db.OpenStorageTrie(l.liquidationPrice, types.EmptyRootHash) s.trie, _ = db.OpenStorageTrie(s.liquidationPrice, types.EmptyRootHash)
l.setError(fmt.Errorf("can't create storage trie: %v", err)) s.setError(fmt.Errorf("can't create storage trie: %v", err))
} }
} }
return l.trie return s.trie
} }
func (l *liquidationPriceState) updateTrie(db Database) Trie { func (s *liquidationPriceState) updateTrie(db Database) Trie {
tr := l.getTrie(db) tr := s.getTrie(db)
for lendingId, stateObject := range l.stateLendingBooks { for lendingId, stateObject := range s.stateLendingBooks {
delete(l.stateLendingBooksDirty, lendingId) delete(s.stateLendingBooksDirty, lendingId)
if stateObject.empty() { if stateObject.empty() {
l.setError(tr.TryDelete(lendingId[:])) s.setError(tr.TryDelete(lendingId[:]))
continue continue
} }
err := stateObject.updateRoot(db) err := stateObject.updateRoot(db)
@ -126,17 +126,17 @@ func (l *liquidationPriceState) updateTrie(db Database) Trie {
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(stateObject) v, _ := rlp.EncodeToBytes(stateObject)
l.setError(tr.TryUpdate(lendingId[:], v)) s.setError(tr.TryUpdate(lendingId[:], v))
} }
return tr return tr
} }
func (l *liquidationPriceState) updateRoot(db Database) error { func (s *liquidationPriceState) updateRoot(db Database) error {
l.updateTrie(db) s.updateTrie(db)
if l.dbErr != nil { if s.dbErr != nil {
return l.dbErr return s.dbErr
} }
root, err := l.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error { root, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error {
var orderList orderList var orderList orderList
if err := rlp.DecodeBytes(leaf, &orderList); err != nil { if err := rlp.DecodeBytes(leaf, &orderList); err != nil {
return nil return nil
@ -147,57 +147,57 @@ func (l *liquidationPriceState) updateRoot(db Database) error {
return nil return nil
}) })
if err == nil { if err == nil {
l.data.Root = root s.data.Root = root
} }
return err return err
} }
func (l *liquidationPriceState) deepCopy(db *TradingStateDB, onDirty func(liquidationPrice common.Hash)) *liquidationPriceState { func (s *liquidationPriceState) deepCopy(db *TradingStateDB, onDirty func(liquidationPrice common.Hash)) *liquidationPriceState {
stateOrderList := newLiquidationPriceState(db, l.orderBook, l.liquidationPrice, l.data, onDirty) stateOrderList := newLiquidationPriceState(db, s.orderBook, s.liquidationPrice, s.data, onDirty)
if l.trie != nil { if s.trie != nil {
stateOrderList.trie = db.db.CopyTrie(l.trie) stateOrderList.trie = db.db.CopyTrie(s.trie)
} }
for key, value := range l.stateLendingBooks { for key, value := range s.stateLendingBooks {
stateOrderList.stateLendingBooks[key] = value.deepCopy(db, l.MarkStateLendingBookDirty) stateOrderList.stateLendingBooks[key] = value.deepCopy(db, s.MarkStateLendingBookDirty)
} }
for key, value := range l.stateLendingBooksDirty { for key, value := range s.stateLendingBooksDirty {
stateOrderList.stateLendingBooksDirty[key] = value stateOrderList.stateLendingBooksDirty[key] = value
} }
return stateOrderList return stateOrderList
} }
// Retrieve a state object given by the address. Returns nil if not found. // Retrieve a state object given by the address. Returns nil if not found.
func (l *liquidationPriceState) getStateLendingBook(db Database, lendingBook common.Hash) (stateObject *stateLendingBook) { func (s *liquidationPriceState) getStateLendingBook(db Database, lendingBook common.Hash) (stateObject *stateLendingBook) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := l.stateLendingBooks[lendingBook]; obj != nil { if obj := s.stateLendingBooks[lendingBook]; obj != nil {
return obj return obj
} }
// Load the object from the database. // Load the object from the database.
enc, err := l.getTrie(db).TryGet(lendingBook[:]) enc, err := s.getTrie(db).TryGet(lendingBook[:])
if len(enc) == 0 { if len(enc) == 0 {
l.setError(err) s.setError(err)
return nil return nil
} }
var data orderList var data orderList
if err := rlp.DecodeBytes(enc, &data); err != nil { if err := rlp.DecodeBytes(enc, &data); err != nil {
log.Error("Failed to decode state lending book ", "orderbook", l.orderBook, "liquidation price", l.liquidationPrice, "lendingBook", lendingBook, "err", err) log.Error("Failed to decode state lending book ", "orderbook", s.orderBook, "liquidation price", s.liquidationPrice, "lendingBook", lendingBook, "err", err)
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newStateLendingBook(l.orderBook, l.liquidationPrice, lendingBook, data, l.MarkStateLendingBookDirty) obj := newStateLendingBook(s.orderBook, s.liquidationPrice, lendingBook, data, s.MarkStateLendingBookDirty)
l.stateLendingBooks[lendingBook] = obj s.stateLendingBooks[lendingBook] = obj
return obj return obj
} }
func (l *liquidationPriceState) getAllLiquidationData(db Database) map[common.Hash][]common.Hash { func (s *liquidationPriceState) getAllLiquidationData(db Database) map[common.Hash][]common.Hash {
liquidationData := map[common.Hash][]common.Hash{} liquidationData := map[common.Hash][]common.Hash{}
lendingBookTrie := l.getTrie(db) lendingBookTrie := s.getTrie(db)
if lendingBookTrie == nil { if lendingBookTrie == nil {
return liquidationData return liquidationData
} }
lendingBooks := []common.Hash{} lendingBooks := []common.Hash{}
for id, stateLendingBook := range l.stateLendingBooks { for id, stateLendingBook := range s.stateLendingBooks {
if !stateLendingBook.empty() { if !stateLendingBook.empty() {
lendingBooks = append(lendingBooks, id) lendingBooks = append(lendingBooks, id)
} }
@ -205,13 +205,13 @@ func (l *liquidationPriceState) getAllLiquidationData(db Database) map[common.Ha
lendingBookListIt := trie.NewIterator(lendingBookTrie.NodeIterator(nil)) lendingBookListIt := trie.NewIterator(lendingBookTrie.NodeIterator(nil))
for lendingBookListIt.Next() { for lendingBookListIt.Next() {
id := common.BytesToHash(lendingBookListIt.Key) id := common.BytesToHash(lendingBookListIt.Key)
if _, exist := l.stateLendingBooks[id]; exist { if _, exist := s.stateLendingBooks[id]; exist {
continue continue
} }
lendingBooks = append(lendingBooks, id) lendingBooks = append(lendingBooks, id)
} }
for _, lendingBook := range lendingBooks { for _, lendingBook := range lendingBooks {
stateLendingBook := l.getStateLendingBook(db, lendingBook) stateLendingBook := s.getStateLendingBook(db, lendingBook)
if stateLendingBook != nil { if stateLendingBook != nil {
liquidationData[lendingBook] = stateLendingBook.getAllTradeIds(db) liquidationData[lendingBook] = stateLendingBook.getAllTradeIds(db)
} }
@ -219,22 +219,22 @@ func (l *liquidationPriceState) getAllLiquidationData(db Database) map[common.Ha
return liquidationData return liquidationData
} }
func (l *liquidationPriceState) AddVolume(amount *big.Int) { func (s *liquidationPriceState) AddVolume(amount *big.Int) {
l.setVolume(new(big.Int).Add(l.data.Volume, amount)) s.setVolume(new(big.Int).Add(s.data.Volume, amount))
} }
func (c *liquidationPriceState) subVolume(amount *big.Int) { func (s *liquidationPriceState) subVolume(amount *big.Int) {
c.setVolume(new(big.Int).Sub(c.data.Volume, amount)) s.setVolume(new(big.Int).Sub(s.data.Volume, amount))
} }
func (l *liquidationPriceState) setVolume(volume *big.Int) { func (s *liquidationPriceState) setVolume(volume *big.Int) {
l.data.Volume = volume s.data.Volume = volume
if l.onDirty != nil { if s.onDirty != nil {
l.onDirty(l.liquidationPrice) s.onDirty(s.liquidationPrice)
l.onDirty = nil s.onDirty = nil
} }
} }
func (l *liquidationPriceState) Volume() *big.Int { func (s *liquidationPriceState) Volume() *big.Int {
return l.data.Volume return s.data.Volume
} }

View file

@ -87,16 +87,16 @@ func (s *stateOrderList) setError(err error) {
} }
} }
func (c *stateOrderList) getTrie(db Database) Trie { func (s *stateOrderList) getTrie(db Database) Trie {
if c.trie == nil { if s.trie == nil {
var err error var err error
c.trie, err = db.OpenStorageTrie(c.price, c.data.Root) s.trie, err = db.OpenStorageTrie(s.price, s.data.Root)
if err != nil { if err != nil {
c.trie, _ = db.OpenStorageTrie(c.price, types.EmptyRootHash) s.trie, _ = db.OpenStorageTrie(s.price, types.EmptyRootHash)
c.setError(fmt.Errorf("can't create storage trie: %v", err)) s.setError(fmt.Errorf("can't create storage trie: %v", err))
} }
} }
return c.trie return s.trie
} }
// GetState returns a value in orderId storage. // GetState returns a value in orderId storage.

View file

@ -557,31 +557,31 @@ func (te *tradingExchanges) MarkStateOrderObjectDirty(orderId common.Hash) {
// createStateOrderListObject creates a new state object. If there is an existing orderId with // createStateOrderListObject creates a new state object. If there is an existing orderId with
// the given address, it is overwritten and returned as the second return value. // the given address, it is overwritten and returned as the second return value.
func (t *tradingExchanges) createStateOrderObject(db Database, orderId common.Hash, order OrderItem) (newobj *stateOrderItem) { func (te *tradingExchanges) createStateOrderObject(db Database, orderId common.Hash, order OrderItem) (newobj *stateOrderItem) {
newobj = newStateOrderItem(t.orderBookHash, orderId, order, t.MarkStateOrderObjectDirty) newobj = newStateOrderItem(te.orderBookHash, orderId, order, te.MarkStateOrderObjectDirty)
orderIdHash := common.BigToHash(new(big.Int).SetUint64(order.OrderID)) orderIdHash := common.BigToHash(new(big.Int).SetUint64(order.OrderID))
t.stateOrderObjects[orderIdHash] = newobj te.stateOrderObjects[orderIdHash] = newobj
t.stateOrderObjectsDirty[orderIdHash] = struct{}{} te.stateOrderObjectsDirty[orderIdHash] = struct{}{}
if t.onDirty != nil { if te.onDirty != nil {
t.onDirty(t.orderBookHash) te.onDirty(te.orderBookHash)
t.onDirty = nil te.onDirty = nil
} }
return newobj return newobj
} }
// updateAskTrie writes cached storage modifications into the object's storage trie. // updateAskTrie writes cached storage modifications into the object's storage trie.
func (t *tradingExchanges) updateOrdersTrie(db Database) Trie { func (te *tradingExchanges) updateOrdersTrie(db Database) Trie {
tr := t.getOrdersTrie(db) tr := te.getOrdersTrie(db)
for orderId, orderItem := range t.stateOrderObjects { for orderId, orderItem := range te.stateOrderObjects {
if _, isDirty := t.stateOrderObjectsDirty[orderId]; isDirty { if _, isDirty := te.stateOrderObjectsDirty[orderId]; isDirty {
delete(t.stateOrderObjectsDirty, orderId) delete(te.stateOrderObjectsDirty, orderId)
if orderItem.empty() { if orderItem.empty() {
t.setError(tr.TryDelete(orderId[:])) te.setError(tr.TryDelete(orderId[:]))
continue continue
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(orderItem) v, _ := rlp.EncodeToBytes(orderItem)
t.setError(tr.TryUpdate(orderId[:], v)) te.setError(tr.TryUpdate(orderId[:], v))
} }
} }
return tr return tr
@ -589,71 +589,71 @@ func (t *tradingExchanges) updateOrdersTrie(db Database) Trie {
// CommitAskTrie the storage trie of the object to db. // CommitAskTrie the storage trie of the object to db.
// This updates the trie root. // This updates the trie root.
func (t *tradingExchanges) updateOrdersRoot(db Database) { func (te *tradingExchanges) updateOrdersRoot(db Database) {
t.updateOrdersTrie(db) te.updateOrdersTrie(db)
t.data.OrderRoot = t.ordersTrie.Hash() te.data.OrderRoot = te.ordersTrie.Hash()
} }
// CommitAskTrie the storage trie of the object to db. // CommitAskTrie the storage trie of the object to db.
// This updates the trie root. // This updates the trie root.
func (t *tradingExchanges) CommitOrdersTrie(db Database) error { func (te *tradingExchanges) CommitOrdersTrie(db Database) error {
t.updateOrdersTrie(db) te.updateOrdersTrie(db)
if t.dbErr != nil { if te.dbErr != nil {
return t.dbErr return te.dbErr
} }
root, err := t.ordersTrie.Commit(nil) root, err := te.ordersTrie.Commit(nil)
if err == nil { if err == nil {
t.data.OrderRoot = root te.data.OrderRoot = root
} }
return err return err
} }
func (t *tradingExchanges) MarkStateLiquidationPriceDirty(price common.Hash) { func (te *tradingExchanges) MarkStateLiquidationPriceDirty(price common.Hash) {
t.liquidationPriceStatesDirty[price] = struct{}{} te.liquidationPriceStatesDirty[price] = struct{}{}
if t.onDirty != nil { if te.onDirty != nil {
t.onDirty(t.Hash()) te.onDirty(te.Hash())
t.onDirty = nil te.onDirty = nil
} }
} }
func (t *tradingExchanges) createStateLiquidationPrice(db Database, liquidationPrice common.Hash) (newobj *liquidationPriceState) { func (te *tradingExchanges) createStateLiquidationPrice(db Database, liquidationPrice common.Hash) (newobj *liquidationPriceState) {
newobj = newLiquidationPriceState(t.db, t.orderBookHash, liquidationPrice, orderList{Volume: Zero}, t.MarkStateLiquidationPriceDirty) newobj = newLiquidationPriceState(te.db, te.orderBookHash, liquidationPrice, orderList{Volume: Zero}, te.MarkStateLiquidationPriceDirty)
t.liquidationPriceStates[liquidationPrice] = newobj te.liquidationPriceStates[liquidationPrice] = newobj
t.liquidationPriceStatesDirty[liquidationPrice] = struct{}{} te.liquidationPriceStatesDirty[liquidationPrice] = struct{}{}
data, err := rlp.EncodeToBytes(newobj) data, err := rlp.EncodeToBytes(newobj)
if err != nil { if err != nil {
panic(fmt.Errorf("can't encode liquidation price object at %x: %v", liquidationPrice[:], err)) panic(fmt.Errorf("can't encode liquidation price object at %x: %v", liquidationPrice[:], err))
} }
t.setError(t.getLiquidationPriceTrie(db).TryUpdate(liquidationPrice[:], data)) te.setError(te.getLiquidationPriceTrie(db).TryUpdate(liquidationPrice[:], data))
if t.onDirty != nil { if te.onDirty != nil {
t.onDirty(t.Hash()) te.onDirty(te.Hash())
t.onDirty = nil te.onDirty = nil
} }
return newobj return newobj
} }
func (t *tradingExchanges) getLiquidationPriceTrie(db Database) Trie { func (te *tradingExchanges) getLiquidationPriceTrie(db Database) Trie {
if t.liquidationPriceTrie == nil { if te.liquidationPriceTrie == nil {
var err error var err error
t.liquidationPriceTrie, err = db.OpenStorageTrie(t.orderBookHash, t.data.LiquidationPriceRoot) te.liquidationPriceTrie, err = db.OpenStorageTrie(te.orderBookHash, te.data.LiquidationPriceRoot)
if err != nil { if err != nil {
t.liquidationPriceTrie, _ = db.OpenStorageTrie(t.orderBookHash, types.EmptyRootHash) te.liquidationPriceTrie, _ = db.OpenStorageTrie(te.orderBookHash, types.EmptyRootHash)
t.setError(fmt.Errorf("can't create liquidation liquidationPrice trie: %v", err)) te.setError(fmt.Errorf("can't create liquidation liquidationPrice trie: %v", err))
} }
} }
return t.liquidationPriceTrie return te.liquidationPriceTrie
} }
func (t *tradingExchanges) getStateLiquidationPrice(db Database, price common.Hash) (stateObject *liquidationPriceState) { func (te *tradingExchanges) getStateLiquidationPrice(db Database, price common.Hash) (stateObject *liquidationPriceState) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := t.liquidationPriceStates[price]; obj != nil { if obj := te.liquidationPriceStates[price]; obj != nil {
return obj return obj
} }
// Load the object from the database. // Load the object from the database.
enc, err := t.getLiquidationPriceTrie(db).TryGet(price[:]) enc, err := te.getLiquidationPriceTrie(db).TryGet(price[:])
if len(enc) == 0 { if len(enc) == 0 {
t.setError(err) te.setError(err)
return nil return nil
} }
var data orderList var data orderList
@ -662,16 +662,16 @@ func (t *tradingExchanges) getStateLiquidationPrice(db Database, price common.Ha
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newLiquidationPriceState(t.db, t.orderBookHash, price, data, t.MarkStateLiquidationPriceDirty) obj := newLiquidationPriceState(te.db, te.orderBookHash, price, data, te.MarkStateLiquidationPriceDirty)
t.liquidationPriceStates[price] = obj te.liquidationPriceStates[price] = obj
return obj return obj
} }
func (t *tradingExchanges) getLowestLiquidationPrice(db Database) (common.Hash, *liquidationPriceState) { func (te *tradingExchanges) getLowestLiquidationPrice(db Database) (common.Hash, *liquidationPriceState) {
trie := t.getLiquidationPriceTrie(db) trie := te.getLiquidationPriceTrie(db)
encKey, encValue, err := trie.TryGetBestLeftKeyAndValue() encKey, encValue, err := trie.TryGetBestLeftKeyAndValue()
if err != nil { if err != nil {
log.Error("Failed find best liquidationPrice ask trie ", "orderbook", t.orderBookHash.Hex()) log.Error("Failed find best liquidationPrice ask trie ", "orderbook", te.orderBookHash.Hex())
return EmptyHash, nil return EmptyHash, nil
} }
if len(encKey) == 0 || len(encValue) == 0 { if len(encKey) == 0 || len(encValue) == 0 {
@ -679,25 +679,25 @@ func (t *tradingExchanges) getLowestLiquidationPrice(db Database) (common.Hash,
return EmptyHash, nil return EmptyHash, nil
} }
price := common.BytesToHash(encKey) price := common.BytesToHash(encKey)
obj := t.liquidationPriceStates[price] obj := te.liquidationPriceStates[price]
if obj == nil { if obj == nil {
var data orderList var data orderList
if err := rlp.DecodeBytes(encValue, &data); err != nil { if err := rlp.DecodeBytes(encValue, &data); err != nil {
log.Error("Failed to decode state get best ask trie", "err", err) log.Error("Failed to decode state get best ask trie", "err", err)
return EmptyHash, nil return EmptyHash, nil
} }
obj = newLiquidationPriceState(t.db, t.orderBookHash, price, data, t.MarkStateLiquidationPriceDirty) obj = newLiquidationPriceState(te.db, te.orderBookHash, price, data, te.MarkStateLiquidationPriceDirty)
t.liquidationPriceStates[price] = obj te.liquidationPriceStates[price] = obj
} }
return price, obj return price, obj
} }
func (t *tradingExchanges) getAllLowerLiquidationPrice(db Database, limit common.Hash) map[common.Hash]*liquidationPriceState { func (te *tradingExchanges) getAllLowerLiquidationPrice(db Database, limit common.Hash) map[common.Hash]*liquidationPriceState {
trie := t.getLiquidationPriceTrie(db) trie := te.getLiquidationPriceTrie(db)
encKeys, encValues, err := trie.TryGetAllLeftKeyAndValue(limit.Bytes()) encKeys, encValues, err := trie.TryGetAllLeftKeyAndValue(limit.Bytes())
result := map[common.Hash]*liquidationPriceState{} result := map[common.Hash]*liquidationPriceState{}
if err != nil || len(encKeys) != len(encValues) { if err != nil || len(encKeys) != len(encValues) {
log.Error("Failed get lower liquidation price trie ", "orderbook", t.orderBookHash.Hex(), "encKeys", len(encKeys), "encValues", len(encValues)) log.Error("Failed get lower liquidation price trie ", "orderbook", te.orderBookHash.Hex(), "encKeys", len(encKeys), "encValues", len(encValues))
return result return result
} }
if len(encKeys) == 0 || len(encValues) == 0 { if len(encKeys) == 0 || len(encValues) == 0 {
@ -706,15 +706,15 @@ func (t *tradingExchanges) getAllLowerLiquidationPrice(db Database, limit common
} }
for i := range encKeys { for i := range encKeys {
price := common.BytesToHash(encKeys[i]) price := common.BytesToHash(encKeys[i])
obj := t.liquidationPriceStates[price] obj := te.liquidationPriceStates[price]
if obj == nil { if obj == nil {
var data orderList var data orderList
if err := rlp.DecodeBytes(encValues[i], &data); err != nil { if err := rlp.DecodeBytes(encValues[i], &data); err != nil {
log.Error("Failed to decode state get all lower liquidation price trie", "price", price, "encValues", encValues[i], "err", err) log.Error("Failed to decode state get all lower liquidation price trie", "price", price, "encValues", encValues[i], "err", err)
return result return result
} }
obj = newLiquidationPriceState(t.db, t.orderBookHash, price, data, t.MarkStateLiquidationPriceDirty) obj = newLiquidationPriceState(te.db, te.orderBookHash, price, data, te.MarkStateLiquidationPriceDirty)
t.liquidationPriceStates[price] = obj te.liquidationPriceStates[price] = obj
} }
if obj.empty() { if obj.empty() {
continue continue
@ -724,11 +724,11 @@ func (t *tradingExchanges) getAllLowerLiquidationPrice(db Database, limit common
return result return result
} }
func (t *tradingExchanges) getHighestLiquidationPrice(db Database) (common.Hash, *liquidationPriceState) { func (te *tradingExchanges) getHighestLiquidationPrice(db Database) (common.Hash, *liquidationPriceState) {
trie := t.getLiquidationPriceTrie(db) trie := te.getLiquidationPriceTrie(db)
encKey, encValue, err := trie.TryGetBestRightKeyAndValue() encKey, encValue, err := trie.TryGetBestRightKeyAndValue()
if err != nil { if err != nil {
log.Error("Failed find best liquidationPrice ask trie ", "orderbook", t.orderBookHash.Hex()) log.Error("Failed find best liquidationPrice ask trie ", "orderbook", te.orderBookHash.Hex())
return EmptyHash, nil return EmptyHash, nil
} }
if len(encKey) == 0 || len(encValue) == 0 { if len(encKey) == 0 || len(encValue) == 0 {
@ -736,15 +736,15 @@ func (t *tradingExchanges) getHighestLiquidationPrice(db Database) (common.Hash,
return EmptyHash, nil return EmptyHash, nil
} }
price := common.BytesToHash(encKey) price := common.BytesToHash(encKey)
obj := t.liquidationPriceStates[price] obj := te.liquidationPriceStates[price]
if obj == nil { if obj == nil {
var data orderList var data orderList
if err := rlp.DecodeBytes(encValue, &data); err != nil { if err := rlp.DecodeBytes(encValue, &data); err != nil {
log.Error("Failed to decode state get best ask trie", "err", err) log.Error("Failed to decode state get best ask trie", "err", err)
return EmptyHash, nil return EmptyHash, nil
} }
obj = newLiquidationPriceState(t.db, t.orderBookHash, price, data, t.MarkStateLiquidationPriceDirty) obj = newLiquidationPriceState(te.db, te.orderBookHash, price, data, te.MarkStateLiquidationPriceDirty)
t.liquidationPriceStates[price] = obj te.liquidationPriceStates[price] = obj
} }
if obj.empty() { if obj.empty() {
return EmptyHash, nil return EmptyHash, nil
@ -752,13 +752,13 @@ func (t *tradingExchanges) getHighestLiquidationPrice(db Database) (common.Hash,
return price, obj return price, obj
} }
func (t *tradingExchanges) updateLiquidationPriceTrie(db Database) Trie { func (te *tradingExchanges) updateLiquidationPriceTrie(db Database) Trie {
tr := t.getLiquidationPriceTrie(db) tr := te.getLiquidationPriceTrie(db)
for price, stateObject := range t.liquidationPriceStates { for price, stateObject := range te.liquidationPriceStates {
if _, isDirty := t.liquidationPriceStatesDirty[price]; isDirty { if _, isDirty := te.liquidationPriceStatesDirty[price]; isDirty {
delete(t.liquidationPriceStatesDirty, price) delete(te.liquidationPriceStatesDirty, price)
if stateObject.empty() { if stateObject.empty() {
t.setError(tr.TryDelete(price[:])) te.setError(tr.TryDelete(price[:]))
continue continue
} }
err := stateObject.updateRoot(db) err := stateObject.updateRoot(db)
@ -767,23 +767,23 @@ func (t *tradingExchanges) updateLiquidationPriceTrie(db Database) Trie {
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(stateObject) v, _ := rlp.EncodeToBytes(stateObject)
t.setError(tr.TryUpdate(price[:], v)) te.setError(tr.TryUpdate(price[:], v))
} }
} }
return tr return tr
} }
func (t *tradingExchanges) updateLiquidationPriceRoot(db Database) { func (te *tradingExchanges) updateLiquidationPriceRoot(db Database) {
t.updateLiquidationPriceTrie(db) te.updateLiquidationPriceTrie(db)
t.data.LiquidationPriceRoot = t.liquidationPriceTrie.Hash() te.data.LiquidationPriceRoot = te.liquidationPriceTrie.Hash()
} }
func (t *tradingExchanges) CommitLiquidationPriceTrie(db Database) error { func (te *tradingExchanges) CommitLiquidationPriceTrie(db Database) error {
t.updateLiquidationPriceTrie(db) te.updateLiquidationPriceTrie(db)
if t.dbErr != nil { if te.dbErr != nil {
return t.dbErr return te.dbErr
} }
root, err := t.liquidationPriceTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error { root, err := te.liquidationPriceTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error {
var orderList orderList var orderList orderList
if err := rlp.DecodeBytes(leaf, &orderList); err != nil { if err := rlp.DecodeBytes(leaf, &orderList); err != nil {
return nil return nil
@ -794,23 +794,23 @@ func (t *tradingExchanges) CommitLiquidationPriceTrie(db Database) error {
return nil return nil
}) })
if err == nil { if err == nil {
t.data.LiquidationPriceRoot = root te.data.LiquidationPriceRoot = root
} }
return err return err
} }
func (t *tradingExchanges) addLendingCount(amount *big.Int) { func (te *tradingExchanges) addLendingCount(amount *big.Int) {
t.setLendingCount(new(big.Int).Add(t.data.LendingCount, amount)) te.setLendingCount(new(big.Int).Add(te.data.LendingCount, amount))
} }
func (t *tradingExchanges) subLendingCount(amount *big.Int) { func (te *tradingExchanges) subLendingCount(amount *big.Int) {
t.setLendingCount(new(big.Int).Sub(t.data.LendingCount, amount)) te.setLendingCount(new(big.Int).Sub(te.data.LendingCount, amount))
} }
func (t *tradingExchanges) setLendingCount(volume *big.Int) { func (te *tradingExchanges) setLendingCount(volume *big.Int) {
t.data.LendingCount = volume te.data.LendingCount = volume
if t.onDirty != nil { if te.onDirty != nil {
t.onDirty(t.orderBookHash) te.onDirty(te.orderBookHash)
t.onDirty = nil te.onDirty = nil
} }
} }

View file

@ -109,14 +109,14 @@ func newStateExchanges(db *LendingStateDB, hash common.Hash, data lendingObject,
} }
// EncodeRLP implements rlp.Encoder. // EncodeRLP implements rlp.Encoder.
func (le *lendingExchangeState) EncodeRLP(w io.Writer) error { func (s *lendingExchangeState) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, le.data) return rlp.Encode(w, s.data)
} }
// setError remembers the first non-nil error it is called with. // setError remembers the first non-nil error it is called with.
func (le *lendingExchangeState) setError(err error) { func (s *lendingExchangeState) setError(err error) {
if le.dbErr == nil { if s.dbErr == nil {
le.dbErr = err s.dbErr = err
} }
} }
@ -124,64 +124,64 @@ func (le *lendingExchangeState) setError(err error) {
Get Trie Get Trie
*/ */
func (le *lendingExchangeState) getLendingItemTrie(db Database) Trie { func (s *lendingExchangeState) getLendingItemTrie(db Database) Trie {
if le.lendingItemTrie == nil { if s.lendingItemTrie == nil {
var err error var err error
le.lendingItemTrie, err = db.OpenStorageTrie(le.lendingBook, le.data.LendingItemRoot) s.lendingItemTrie, err = db.OpenStorageTrie(s.lendingBook, s.data.LendingItemRoot)
if err != nil { if err != nil {
le.lendingItemTrie, _ = db.OpenStorageTrie(le.lendingBook, types.EmptyRootHash) s.lendingItemTrie, _ = db.OpenStorageTrie(s.lendingBook, types.EmptyRootHash)
le.setError(fmt.Errorf("can't create Lendings trie: %v", err)) s.setError(fmt.Errorf("can't create Lendings trie: %v", err))
} }
} }
return le.lendingItemTrie return s.lendingItemTrie
} }
func (le *lendingExchangeState) getLendingTradeTrie(db Database) Trie { func (s *lendingExchangeState) getLendingTradeTrie(db Database) Trie {
if le.lendingTradeTrie == nil { if s.lendingTradeTrie == nil {
var err error var err error
le.lendingTradeTrie, err = db.OpenStorageTrie(le.lendingBook, le.data.LendingTradeRoot) s.lendingTradeTrie, err = db.OpenStorageTrie(s.lendingBook, s.data.LendingTradeRoot)
if err != nil { if err != nil {
le.lendingTradeTrie, _ = db.OpenStorageTrie(le.lendingBook, types.EmptyRootHash) s.lendingTradeTrie, _ = db.OpenStorageTrie(s.lendingBook, types.EmptyRootHash)
le.setError(fmt.Errorf("can't create Lendings trie: %v", err)) s.setError(fmt.Errorf("can't create Lendings trie: %v", err))
} }
} }
return le.lendingTradeTrie return s.lendingTradeTrie
} }
func (le *lendingExchangeState) getInvestingTrie(db Database) Trie { func (s *lendingExchangeState) getInvestingTrie(db Database) Trie {
if le.investingTrie == nil { if s.investingTrie == nil {
var err error var err error
le.investingTrie, err = db.OpenStorageTrie(le.lendingBook, le.data.InvestingRoot) s.investingTrie, err = db.OpenStorageTrie(s.lendingBook, s.data.InvestingRoot)
if err != nil { if err != nil {
le.investingTrie, _ = db.OpenStorageTrie(le.lendingBook, types.EmptyRootHash) s.investingTrie, _ = db.OpenStorageTrie(s.lendingBook, types.EmptyRootHash)
le.setError(fmt.Errorf("can't create Lendings trie: %v", err)) s.setError(fmt.Errorf("can't create Lendings trie: %v", err))
} }
} }
return le.investingTrie return s.investingTrie
} }
func (le *lendingExchangeState) getBorrowingTrie(db Database) Trie { func (s *lendingExchangeState) getBorrowingTrie(db Database) Trie {
if le.borrowingTrie == nil { if s.borrowingTrie == nil {
var err error var err error
le.borrowingTrie, err = db.OpenStorageTrie(le.lendingBook, le.data.BorrowingRoot) s.borrowingTrie, err = db.OpenStorageTrie(s.lendingBook, s.data.BorrowingRoot)
if err != nil { if err != nil {
le.borrowingTrie, _ = db.OpenStorageTrie(le.lendingBook, types.EmptyRootHash) s.borrowingTrie, _ = db.OpenStorageTrie(s.lendingBook, types.EmptyRootHash)
le.setError(fmt.Errorf("can't create bids trie: %v", err)) s.setError(fmt.Errorf("can't create bids trie: %v", err))
} }
} }
return le.borrowingTrie return s.borrowingTrie
} }
func (le *lendingExchangeState) getLiquidationTimeTrie(db Database) Trie { func (s *lendingExchangeState) getLiquidationTimeTrie(db Database) Trie {
if le.liquidationTimeTrie == nil { if s.liquidationTimeTrie == nil {
var err error var err error
le.liquidationTimeTrie, err = db.OpenStorageTrie(le.lendingBook, le.data.LiquidationTimeRoot) s.liquidationTimeTrie, err = db.OpenStorageTrie(s.lendingBook, s.data.LiquidationTimeRoot)
if err != nil { if err != nil {
le.liquidationTimeTrie, _ = db.OpenStorageTrie(le.lendingBook, types.EmptyRootHash) s.liquidationTimeTrie, _ = db.OpenStorageTrie(s.lendingBook, types.EmptyRootHash)
le.setError(fmt.Errorf("can't create bids trie: %v", err)) s.setError(fmt.Errorf("can't create bids trie: %v", err))
} }
} }
return le.liquidationTimeTrie return s.liquidationTimeTrie
} }
/* /*
@ -189,16 +189,16 @@ func (le *lendingExchangeState) getLiquidationTimeTrie(db Database) Trie {
Get State Get State
*/ */
func (le *lendingExchangeState) getBorrowingOrderList(db Database, rate common.Hash) (stateOrderList *itemListState) { func (s *lendingExchangeState) getBorrowingOrderList(db Database, rate common.Hash) (stateOrderList *itemListState) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := le.borrowingStates[rate]; obj != nil { if obj := s.borrowingStates[rate]; obj != nil {
return obj return obj
} }
// Load the object from the database. // Load the object from the database.
enc, err := le.getBorrowingTrie(db).TryGet(rate[:]) enc, err := s.getBorrowingTrie(db).TryGet(rate[:])
if len(enc) == 0 { if len(enc) == 0 {
le.setError(err) s.setError(err)
return nil return nil
} }
var data itemList var data itemList
@ -207,21 +207,21 @@ func (le *lendingExchangeState) getBorrowingOrderList(db Database, rate common.H
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newItemListState(le.lendingBook, rate, data, le.MarkBorrowingDirty) obj := newItemListState(s.lendingBook, rate, data, s.MarkBorrowingDirty)
le.borrowingStates[rate] = obj s.borrowingStates[rate] = obj
return obj return obj
} }
func (le *lendingExchangeState) getInvestingOrderList(db Database, rate common.Hash) (stateOrderList *itemListState) { func (s *lendingExchangeState) getInvestingOrderList(db Database, rate common.Hash) (stateOrderList *itemListState) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := le.investingStates[rate]; obj != nil { if obj := s.investingStates[rate]; obj != nil {
return obj return obj
} }
// Load the object from the database. // Load the object from the database.
enc, err := le.getInvestingTrie(db).TryGet(rate[:]) enc, err := s.getInvestingTrie(db).TryGet(rate[:])
if len(enc) == 0 { if len(enc) == 0 {
le.setError(err) s.setError(err)
return nil return nil
} }
var data itemList var data itemList
@ -230,21 +230,21 @@ func (le *lendingExchangeState) getInvestingOrderList(db Database, rate common.H
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newItemListState(le.lendingBook, rate, data, le.MarkInvestingDirty) obj := newItemListState(s.lendingBook, rate, data, s.MarkInvestingDirty)
le.investingStates[rate] = obj s.investingStates[rate] = obj
return obj return obj
} }
func (le *lendingExchangeState) getLiquidationTimeOrderList(db Database, time common.Hash) (stateObject *liquidationTimeState) { func (s *lendingExchangeState) getLiquidationTimeOrderList(db Database, time common.Hash) (stateObject *liquidationTimeState) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := le.liquidationTimeStates[time]; obj != nil { if obj := s.liquidationTimeStates[time]; obj != nil {
return obj return obj
} }
// Load the object from the database. // Load the object from the database.
enc, err := le.getLiquidationTimeTrie(db).TryGet(time[:]) enc, err := s.getLiquidationTimeTrie(db).TryGet(time[:])
if len(enc) == 0 { if len(enc) == 0 {
le.setError(err) s.setError(err)
return nil return nil
} }
var data itemList var data itemList
@ -253,21 +253,21 @@ func (le *lendingExchangeState) getLiquidationTimeOrderList(db Database, time co
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newLiquidationTimeState(le.lendingBook, time, data, le.MarkLiquidationTimeDirty) obj := newLiquidationTimeState(s.lendingBook, time, data, s.MarkLiquidationTimeDirty)
le.liquidationTimeStates[time] = obj s.liquidationTimeStates[time] = obj
return obj return obj
} }
func (le *lendingExchangeState) getLendingItem(db Database, lendingId common.Hash) (stateObject *lendingItemState) { func (s *lendingExchangeState) getLendingItem(db Database, lendingId common.Hash) (stateObject *lendingItemState) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := le.lendingItemStates[lendingId]; obj != nil { if obj := s.lendingItemStates[lendingId]; obj != nil {
return obj return obj
} }
// Load the object from the database. // Load the object from the database.
enc, err := le.getLendingItemTrie(db).TryGet(lendingId[:]) enc, err := s.getLendingItemTrie(db).TryGet(lendingId[:])
if len(enc) == 0 { if len(enc) == 0 {
le.setError(err) s.setError(err)
return nil return nil
} }
var data LendingItem var data LendingItem
@ -276,21 +276,21 @@ func (le *lendingExchangeState) getLendingItem(db Database, lendingId common.Has
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newLendinItemState(le.lendingBook, lendingId, data, le.MarkLendingItemDirty) obj := newLendinItemState(s.lendingBook, lendingId, data, s.MarkLendingItemDirty)
le.lendingItemStates[lendingId] = obj s.lendingItemStates[lendingId] = obj
return obj return obj
} }
func (le *lendingExchangeState) getLendingTrade(db Database, tradeId common.Hash) (stateObject *lendingTradeState) { func (s *lendingExchangeState) getLendingTrade(db Database, tradeId common.Hash) (stateObject *lendingTradeState) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := le.lendingTradeStates[tradeId]; obj != nil { if obj := s.lendingTradeStates[tradeId]; obj != nil {
return obj return obj
} }
// Load the object from the database. // Load the object from the database.
enc, err := le.getLendingTradeTrie(db).TryGet(tradeId[:]) enc, err := s.getLendingTradeTrie(db).TryGet(tradeId[:])
if len(enc) == 0 { if len(enc) == 0 {
le.setError(err) s.setError(err)
return nil return nil
} }
var data LendingTrade var data LendingTrade
@ -299,8 +299,8 @@ func (le *lendingExchangeState) getLendingTrade(db Database, tradeId common.Hash
return nil return nil
} }
// Insert into the live set. // Insert into the live set.
obj := newLendingTradeState(le.lendingBook, tradeId, data, le.MarkLendingTradeDirty) obj := newLendingTradeState(s.lendingBook, tradeId, data, s.MarkLendingTradeDirty)
le.lendingTradeStates[tradeId] = obj s.lendingTradeStates[tradeId] = obj
return obj return obj
} }
@ -309,47 +309,47 @@ func (le *lendingExchangeState) getLendingTrade(db Database, tradeId common.Hash
Update Trie Update Trie
*/ */
func (le *lendingExchangeState) updateLendingTimeTrie(db Database) Trie { func (s *lendingExchangeState) updateLendingTimeTrie(db Database) Trie {
tr := le.getLendingItemTrie(db) tr := s.getLendingItemTrie(db)
for lendingId, lendingItem := range le.lendingItemStates { for lendingId, lendingItem := range s.lendingItemStates {
if _, isDirty := le.lendingItemStatesDirty[lendingId]; isDirty { if _, isDirty := s.lendingItemStatesDirty[lendingId]; isDirty {
delete(le.lendingItemStatesDirty, lendingId) delete(s.lendingItemStatesDirty, lendingId)
if lendingItem.empty() { if lendingItem.empty() {
le.setError(tr.TryDelete(lendingId[:])) s.setError(tr.TryDelete(lendingId[:]))
continue continue
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(lendingItem) v, _ := rlp.EncodeToBytes(lendingItem)
le.setError(tr.TryUpdate(lendingId[:], v)) s.setError(tr.TryUpdate(lendingId[:], v))
} }
} }
return tr return tr
} }
func (le *lendingExchangeState) updateLendingTradeTrie(db Database) Trie { func (s *lendingExchangeState) updateLendingTradeTrie(db Database) Trie {
tr := le.getLendingTradeTrie(db) tr := s.getLendingTradeTrie(db)
for tradeId, lendingTradeItem := range le.lendingTradeStates { for tradeId, lendingTradeItem := range s.lendingTradeStates {
if _, isDirty := le.lendingTradeStatesDirty[tradeId]; isDirty { if _, isDirty := s.lendingTradeStatesDirty[tradeId]; isDirty {
delete(le.lendingTradeStatesDirty, tradeId) delete(s.lendingTradeStatesDirty, tradeId)
if lendingTradeItem.empty() { if lendingTradeItem.empty() {
le.setError(tr.TryDelete(tradeId[:])) s.setError(tr.TryDelete(tradeId[:]))
continue continue
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(lendingTradeItem) v, _ := rlp.EncodeToBytes(lendingTradeItem)
le.setError(tr.TryUpdate(tradeId[:], v)) s.setError(tr.TryUpdate(tradeId[:], v))
} }
} }
return tr return tr
} }
func (le *lendingExchangeState) updateBorrowingTrie(db Database) Trie { func (s *lendingExchangeState) updateBorrowingTrie(db Database) Trie {
tr := le.getBorrowingTrie(db) tr := s.getBorrowingTrie(db)
for rate, orderList := range le.borrowingStates { for rate, orderList := range s.borrowingStates {
if _, isDirty := le.borrowingStatesDirty[rate]; isDirty { if _, isDirty := s.borrowingStatesDirty[rate]; isDirty {
delete(le.borrowingStatesDirty, rate) delete(s.borrowingStatesDirty, rate)
if orderList.empty() { if orderList.empty() {
le.setError(tr.TryDelete(rate[:])) s.setError(tr.TryDelete(rate[:]))
continue continue
} }
err := orderList.updateRoot(db) err := orderList.updateRoot(db)
@ -358,19 +358,19 @@ func (le *lendingExchangeState) updateBorrowingTrie(db Database) Trie {
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(orderList) v, _ := rlp.EncodeToBytes(orderList)
le.setError(tr.TryUpdate(rate[:], v)) s.setError(tr.TryUpdate(rate[:], v))
} }
} }
return tr return tr
} }
func (le *lendingExchangeState) updateInvestingTrie(db Database) Trie { func (s *lendingExchangeState) updateInvestingTrie(db Database) Trie {
tr := le.getInvestingTrie(db) tr := s.getInvestingTrie(db)
for rate, orderList := range le.investingStates { for rate, orderList := range s.investingStates {
if _, isDirty := le.investingStatesDirty[rate]; isDirty { if _, isDirty := s.investingStatesDirty[rate]; isDirty {
delete(le.investingStatesDirty, rate) delete(s.investingStatesDirty, rate)
if orderList.empty() { if orderList.empty() {
le.setError(tr.TryDelete(rate[:])) s.setError(tr.TryDelete(rate[:]))
continue continue
} }
err := orderList.updateRoot(db) err := orderList.updateRoot(db)
@ -379,19 +379,19 @@ func (le *lendingExchangeState) updateInvestingTrie(db Database) Trie {
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(orderList) v, _ := rlp.EncodeToBytes(orderList)
le.setError(tr.TryUpdate(rate[:], v)) s.setError(tr.TryUpdate(rate[:], v))
} }
} }
return tr return tr
} }
func (le *lendingExchangeState) updateLiquidationTimeTrie(db Database) Trie { func (s *lendingExchangeState) updateLiquidationTimeTrie(db Database) Trie {
tr := le.getLiquidationTimeTrie(db) tr := s.getLiquidationTimeTrie(db)
for time, itemList := range le.liquidationTimeStates { for time, itemList := range s.liquidationTimeStates {
if _, isDirty := le.liquidationTimestatesDirty[time]; isDirty { if _, isDirty := s.liquidationTimestatesDirty[time]; isDirty {
delete(le.liquidationTimestatesDirty, time) delete(s.liquidationTimestatesDirty, time)
if itemList.empty() { if itemList.empty() {
le.setError(tr.TryDelete(time[:])) s.setError(tr.TryDelete(time[:]))
continue continue
} }
err := itemList.updateRoot(db) err := itemList.updateRoot(db)
@ -400,7 +400,7 @@ func (le *lendingExchangeState) updateLiquidationTimeTrie(db Database) Trie {
} }
// Encoding []byte cannot fail, ok to ignore the error. // Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(itemList) v, _ := rlp.EncodeToBytes(itemList)
le.setError(tr.TryUpdate(time[:], v)) s.setError(tr.TryUpdate(time[:], v))
} }
} }
return tr return tr
@ -410,69 +410,69 @@ func (le *lendingExchangeState) updateLiquidationTimeTrie(db Database) Trie {
Update Root Update Root
*/ */
func (le *lendingExchangeState) updateOrderRoot(db Database) { func (s *lendingExchangeState) updateOrderRoot(db Database) {
le.updateLendingTimeTrie(db) s.updateLendingTimeTrie(db)
le.data.LendingItemRoot = le.lendingItemTrie.Hash() s.data.LendingItemRoot = s.lendingItemTrie.Hash()
} }
func (le *lendingExchangeState) updateInvestingRoot(db Database) error { func (s *lendingExchangeState) updateInvestingRoot(db Database) error {
le.updateInvestingTrie(db) s.updateInvestingTrie(db)
if le.dbErr != nil { if s.dbErr != nil {
return le.dbErr return s.dbErr
} }
le.data.InvestingRoot = le.investingTrie.Hash() s.data.InvestingRoot = s.investingTrie.Hash()
return nil return nil
} }
func (le *lendingExchangeState) updateBorrowingRoot(db Database) { func (s *lendingExchangeState) updateBorrowingRoot(db Database) {
le.updateBorrowingTrie(db) s.updateBorrowingTrie(db)
le.data.BorrowingRoot = le.borrowingTrie.Hash() s.data.BorrowingRoot = s.borrowingTrie.Hash()
} }
func (le *lendingExchangeState) updateLiquidationTimeRoot(db Database) { func (s *lendingExchangeState) updateLiquidationTimeRoot(db Database) {
le.updateLiquidationTimeTrie(db) s.updateLiquidationTimeTrie(db)
le.data.LiquidationTimeRoot = le.liquidationTimeTrie.Hash() s.data.LiquidationTimeRoot = s.liquidationTimeTrie.Hash()
} }
func (le *lendingExchangeState) updateLendingTradeRoot(db Database) { func (s *lendingExchangeState) updateLendingTradeRoot(db Database) {
le.updateLendingTradeTrie(db) s.updateLendingTradeTrie(db)
le.data.LendingTradeRoot = le.lendingTradeTrie.Hash() s.data.LendingTradeRoot = s.lendingTradeTrie.Hash()
} }
/** /**
Commit Trie Commit Trie
*/ */
func (le *lendingExchangeState) CommitLendingItemTrie(db Database) error { func (s *lendingExchangeState) CommitLendingItemTrie(db Database) error {
le.updateLendingTimeTrie(db) s.updateLendingTimeTrie(db)
if le.dbErr != nil { if s.dbErr != nil {
return le.dbErr return s.dbErr
} }
root, err := le.lendingItemTrie.Commit(nil) root, err := s.lendingItemTrie.Commit(nil)
if err == nil { if err == nil {
le.data.LendingItemRoot = root s.data.LendingItemRoot = root
} }
return err return err
} }
func (le *lendingExchangeState) CommitLendingTradeTrie(db Database) error { func (s *lendingExchangeState) CommitLendingTradeTrie(db Database) error {
le.updateLendingTradeTrie(db) s.updateLendingTradeTrie(db)
if le.dbErr != nil { if s.dbErr != nil {
return le.dbErr return s.dbErr
} }
root, err := le.lendingTradeTrie.Commit(nil) root, err := s.lendingTradeTrie.Commit(nil)
if err == nil { if err == nil {
le.data.LendingTradeRoot = root s.data.LendingTradeRoot = root
} }
return err return err
} }
func (le *lendingExchangeState) CommitInvestingTrie(db Database) error { func (s *lendingExchangeState) CommitInvestingTrie(db Database) error {
le.updateInvestingTrie(db) s.updateInvestingTrie(db)
if le.dbErr != nil { if s.dbErr != nil {
return le.dbErr return s.dbErr
} }
root, err := le.investingTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error { root, err := s.investingTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error {
var orderList itemList var orderList itemList
if err := rlp.DecodeBytes(leaf, &orderList); err != nil { if err := rlp.DecodeBytes(leaf, &orderList); err != nil {
return nil return nil
@ -483,17 +483,17 @@ func (le *lendingExchangeState) CommitInvestingTrie(db Database) error {
return nil return nil
}) })
if err == nil { if err == nil {
le.data.InvestingRoot = root s.data.InvestingRoot = root
} }
return err return err
} }
func (le *lendingExchangeState) CommitBorrowingTrie(db Database) error { func (s *lendingExchangeState) CommitBorrowingTrie(db Database) error {
le.updateBorrowingTrie(db) s.updateBorrowingTrie(db)
if le.dbErr != nil { if s.dbErr != nil {
return le.dbErr return s.dbErr
} }
root, err := le.borrowingTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error { root, err := s.borrowingTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error {
var orderList itemList var orderList itemList
if err := rlp.DecodeBytes(leaf, &orderList); err != nil { if err := rlp.DecodeBytes(leaf, &orderList); err != nil {
return nil return nil
@ -504,17 +504,17 @@ func (le *lendingExchangeState) CommitBorrowingTrie(db Database) error {
return nil return nil
}) })
if err == nil { if err == nil {
le.data.BorrowingRoot = root s.data.BorrowingRoot = root
} }
return err return err
} }
func (le *lendingExchangeState) CommitLiquidationTimeTrie(db Database) error { func (s *lendingExchangeState) CommitLiquidationTimeTrie(db Database) error {
le.updateLiquidationTimeTrie(db) s.updateLiquidationTimeTrie(db)
if le.dbErr != nil { if s.dbErr != nil {
return le.dbErr return s.dbErr
} }
root, err := le.liquidationTimeTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error { root, err := s.liquidationTimeTrie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash, _ []byte) error {
var orderList itemList var orderList itemList
if err := rlp.DecodeBytes(leaf, &orderList); err != nil { if err := rlp.DecodeBytes(leaf, &orderList); err != nil {
return nil return nil
@ -525,7 +525,7 @@ func (le *lendingExchangeState) CommitLiquidationTimeTrie(db Database) error {
return nil return nil
}) })
if err == nil { if err == nil {
le.data.LiquidationTimeRoot = root s.data.LiquidationTimeRoot = root
} }
return err return err
} }
@ -535,11 +535,11 @@ func (le *lendingExchangeState) CommitLiquidationTimeTrie(db Database) error {
Get Trie Data Get Trie Data
*/ */
func (le *lendingExchangeState) getBestInvestingInterest(db Database) common.Hash { func (s *lendingExchangeState) getBestInvestingInterest(db Database) common.Hash {
trie := le.getInvestingTrie(db) trie := s.getInvestingTrie(db)
encKey, encValue, err := trie.TryGetBestLeftKeyAndValue() encKey, encValue, err := trie.TryGetBestLeftKeyAndValue()
if err != nil { if err != nil {
log.Error("Failed find best investing rate", "orderbook", le.lendingBook.Hex()) log.Error("Failed find best investing rate", "orderbook", s.lendingBook.Hex())
return EmptyHash return EmptyHash
} }
if len(encKey) == 0 || len(encValue) == 0 { if len(encKey) == 0 || len(encValue) == 0 {
@ -548,23 +548,23 @@ func (le *lendingExchangeState) getBestInvestingInterest(db Database) common.Has
} }
// Insert into the live set. // Insert into the live set.
interest := common.BytesToHash(encKey) interest := common.BytesToHash(encKey)
if _, exist := le.investingStates[interest]; !exist { if _, exist := s.investingStates[interest]; !exist {
var data itemList var data itemList
if err := rlp.DecodeBytes(encValue, &data); err != nil { if err := rlp.DecodeBytes(encValue, &data); err != nil {
log.Error("Failed to decode state get best investing rate", "err", err) log.Error("Failed to decode state get best investing rate", "err", err)
return EmptyHash return EmptyHash
} }
obj := newItemListState(le.lendingBook, interest, data, le.MarkInvestingDirty) obj := newItemListState(s.lendingBook, interest, data, s.MarkInvestingDirty)
le.investingStates[interest] = obj s.investingStates[interest] = obj
} }
return interest return interest
} }
func (le *lendingExchangeState) getBestBorrowingInterest(db Database) common.Hash { func (s *lendingExchangeState) getBestBorrowingInterest(db Database) common.Hash {
trie := le.getBorrowingTrie(db) trie := s.getBorrowingTrie(db)
encKey, encValue, err := trie.TryGetBestRightKeyAndValue() encKey, encValue, err := trie.TryGetBestRightKeyAndValue()
if err != nil { if err != nil {
log.Error("Failed find best key bid trie ", "orderbook", le.lendingBook.Hex()) log.Error("Failed find best key bid trie ", "orderbook", s.lendingBook.Hex())
return EmptyHash return EmptyHash
} }
if len(encKey) == 0 || len(encValue) == 0 { if len(encKey) == 0 || len(encValue) == 0 {
@ -573,23 +573,23 @@ func (le *lendingExchangeState) getBestBorrowingInterest(db Database) common.Has
} }
// Insert into the live set. // Insert into the live set.
interest := common.BytesToHash(encKey) interest := common.BytesToHash(encKey)
if _, exist := le.borrowingStates[interest]; !exist { if _, exist := s.borrowingStates[interest]; !exist {
var data itemList var data itemList
if err := rlp.DecodeBytes(encValue, &data); err != nil { if err := rlp.DecodeBytes(encValue, &data); err != nil {
log.Error("Failed to decode state get best bid trie", "err", err) log.Error("Failed to decode state get best bid trie", "err", err)
return EmptyHash return EmptyHash
} }
obj := newItemListState(le.lendingBook, interest, data, le.MarkBorrowingDirty) obj := newItemListState(s.lendingBook, interest, data, s.MarkBorrowingDirty)
le.borrowingStates[interest] = obj s.borrowingStates[interest] = obj
} }
return interest return interest
} }
func (le *lendingExchangeState) getLowestLiquidationTime(db Database) (common.Hash, *liquidationTimeState) { func (s *lendingExchangeState) getLowestLiquidationTime(db Database) (common.Hash, *liquidationTimeState) {
trie := le.getLiquidationTimeTrie(db) trie := s.getLiquidationTimeTrie(db)
encKey, encValue, err := trie.TryGetBestLeftKeyAndValue() encKey, encValue, err := trie.TryGetBestLeftKeyAndValue()
if err != nil { if err != nil {
log.Error("Failed find best liquidation time trie ", "orderBook", le.lendingBook.Hex()) log.Error("Failed find best liquidation time trie ", "orderBook", s.lendingBook.Hex())
return EmptyHash, nil return EmptyHash, nil
} }
if len(encKey) == 0 || len(encValue) == 0 { if len(encKey) == 0 || len(encValue) == 0 {
@ -597,15 +597,15 @@ func (le *lendingExchangeState) getLowestLiquidationTime(db Database) (common.Ha
return EmptyHash, nil return EmptyHash, nil
} }
price := common.BytesToHash(encKey) price := common.BytesToHash(encKey)
obj, exist := le.liquidationTimeStates[price] obj, exist := s.liquidationTimeStates[price]
if !exist { if !exist {
var data itemList var data itemList
if err := rlp.DecodeBytes(encValue, &data); err != nil { if err := rlp.DecodeBytes(encValue, &data); err != nil {
log.Error("Failed to decode state get liquidation time trie", "err", err) log.Error("Failed to decode state get liquidation time trie", "err", err)
return EmptyHash, nil return EmptyHash, nil
} }
obj = newLiquidationTimeState(le.lendingBook, price, data, le.MarkLiquidationTimeDirty) obj = newLiquidationTimeState(s.lendingBook, price, data, s.MarkLiquidationTimeDirty)
le.liquidationTimeStates[price] = obj s.liquidationTimeStates[price] = obj
} }
if obj.empty() { if obj.empty() {
return EmptyHash, nil return EmptyHash, nil
@ -613,194 +613,194 @@ func (le *lendingExchangeState) getLowestLiquidationTime(db Database) (common.Ha
return price, obj return price, obj
} }
func (le *lendingExchangeState) deepCopy(db *LendingStateDB, onDirty func(hash common.Hash)) *lendingExchangeState { func (s *lendingExchangeState) deepCopy(db *LendingStateDB, onDirty func(hash common.Hash)) *lendingExchangeState {
stateExchanges := newStateExchanges(db, le.lendingBook, le.data, onDirty) stateExchanges := newStateExchanges(db, s.lendingBook, s.data, onDirty)
if le.investingTrie != nil { if s.investingTrie != nil {
stateExchanges.investingTrie = db.db.CopyTrie(le.investingTrie) stateExchanges.investingTrie = db.db.CopyTrie(s.investingTrie)
} }
if le.borrowingTrie != nil { if s.borrowingTrie != nil {
stateExchanges.borrowingTrie = db.db.CopyTrie(le.borrowingTrie) stateExchanges.borrowingTrie = db.db.CopyTrie(s.borrowingTrie)
} }
if le.lendingItemTrie != nil { if s.lendingItemTrie != nil {
stateExchanges.lendingItemTrie = db.db.CopyTrie(le.lendingItemTrie) stateExchanges.lendingItemTrie = db.db.CopyTrie(s.lendingItemTrie)
} }
for key, value := range le.borrowingStates { for key, value := range s.borrowingStates {
stateExchanges.borrowingStates[key] = value.deepCopy(db, le.MarkBorrowingDirty) stateExchanges.borrowingStates[key] = value.deepCopy(db, s.MarkBorrowingDirty)
} }
for key := range le.borrowingStatesDirty { for key := range s.borrowingStatesDirty {
stateExchanges.borrowingStatesDirty[key] = struct{}{} stateExchanges.borrowingStatesDirty[key] = struct{}{}
} }
for key, value := range le.investingStates { for key, value := range s.investingStates {
stateExchanges.investingStates[key] = value.deepCopy(db, le.MarkInvestingDirty) stateExchanges.investingStates[key] = value.deepCopy(db, s.MarkInvestingDirty)
} }
for key := range le.investingStatesDirty { for key := range s.investingStatesDirty {
stateExchanges.investingStatesDirty[key] = struct{}{} stateExchanges.investingStatesDirty[key] = struct{}{}
} }
for key, value := range le.lendingItemStates { for key, value := range s.lendingItemStates {
stateExchanges.lendingItemStates[key] = value.deepCopy(le.MarkLendingItemDirty) stateExchanges.lendingItemStates[key] = value.deepCopy(s.MarkLendingItemDirty)
} }
for orderId := range le.lendingItemStatesDirty { for orderId := range s.lendingItemStatesDirty {
stateExchanges.lendingItemStatesDirty[orderId] = struct{}{} stateExchanges.lendingItemStatesDirty[orderId] = struct{}{}
} }
for key, value := range le.lendingTradeStates { for key, value := range s.lendingTradeStates {
stateExchanges.lendingTradeStates[key] = value.deepCopy(le.MarkLendingTradeDirty) stateExchanges.lendingTradeStates[key] = value.deepCopy(s.MarkLendingTradeDirty)
} }
for orderId := range le.lendingTradeStatesDirty { for orderId := range s.lendingTradeStatesDirty {
stateExchanges.lendingTradeStatesDirty[orderId] = struct{}{} stateExchanges.lendingTradeStatesDirty[orderId] = struct{}{}
} }
for time, orderList := range le.liquidationTimeStates { for time, orderList := range s.liquidationTimeStates {
stateExchanges.liquidationTimeStates[time] = orderList.deepCopy(db, le.MarkLiquidationTimeDirty) stateExchanges.liquidationTimeStates[time] = orderList.deepCopy(db, s.MarkLiquidationTimeDirty)
} }
for time := range le.liquidationTimestatesDirty { for time := range s.liquidationTimestatesDirty {
stateExchanges.liquidationTimestatesDirty[time] = struct{}{} stateExchanges.liquidationTimestatesDirty[time] = struct{}{}
} }
return stateExchanges return stateExchanges
} }
// Returns the address of the contract/tradeId // Returns the address of the contract/tradeId
func (le *lendingExchangeState) Hash() common.Hash { func (s *lendingExchangeState) Hash() common.Hash {
return le.lendingBook return s.lendingBook
} }
func (le *lendingExchangeState) setNonce(nonce uint64) { func (s *lendingExchangeState) setNonce(nonce uint64) {
le.data.Nonce = nonce s.data.Nonce = nonce
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
} }
func (le *lendingExchangeState) Nonce() uint64 { func (s *lendingExchangeState) Nonce() uint64 {
return le.data.Nonce return s.data.Nonce
} }
func (le *lendingExchangeState) setTradeNonce(nonce uint64) { func (s *lendingExchangeState) setTradeNonce(nonce uint64) {
le.data.TradeNonce = nonce s.data.TradeNonce = nonce
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
} }
func (le *lendingExchangeState) TradeNonce() uint64 { func (s *lendingExchangeState) TradeNonce() uint64 {
return le.data.TradeNonce return s.data.TradeNonce
} }
func (le *lendingExchangeState) removeInvestingOrderList(db Database, stateOrderList *itemListState) { func (s *lendingExchangeState) removeInvestingOrderList(db Database, stateOrderList *itemListState) {
le.setError(le.investingTrie.TryDelete(stateOrderList.key[:])) s.setError(s.investingTrie.TryDelete(stateOrderList.key[:]))
} }
func (le *lendingExchangeState) removeBorrowingOrderList(db Database, stateOrderList *itemListState) { func (s *lendingExchangeState) removeBorrowingOrderList(db Database, stateOrderList *itemListState) {
le.setError(le.borrowingTrie.TryDelete(stateOrderList.key[:])) s.setError(s.borrowingTrie.TryDelete(stateOrderList.key[:]))
} }
func (le *lendingExchangeState) createInvestingOrderList(db Database, price common.Hash) (newobj *itemListState) { func (s *lendingExchangeState) createInvestingOrderList(db Database, price common.Hash) (newobj *itemListState) {
newobj = newItemListState(le.lendingBook, price, itemList{Volume: Zero}, le.MarkInvestingDirty) newobj = newItemListState(s.lendingBook, price, itemList{Volume: Zero}, s.MarkInvestingDirty)
le.investingStates[price] = newobj s.investingStates[price] = newobj
le.investingStatesDirty[price] = struct{}{} s.investingStatesDirty[price] = struct{}{}
data, err := rlp.EncodeToBytes(newobj) data, err := rlp.EncodeToBytes(newobj)
if err != nil { if err != nil {
panic(fmt.Errorf("can't encode order list object at %x: %v", price[:], err)) panic(fmt.Errorf("can't encode order list object at %x: %v", price[:], err))
} }
le.setError(le.getInvestingTrie(db).TryUpdate(price[:], data)) s.setError(s.getInvestingTrie(db).TryUpdate(price[:], data))
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
return newobj return newobj
} }
func (le *lendingExchangeState) MarkBorrowingDirty(price common.Hash) { func (s *lendingExchangeState) MarkBorrowingDirty(price common.Hash) {
le.borrowingStatesDirty[price] = struct{}{} s.borrowingStatesDirty[price] = struct{}{}
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
} }
func (le *lendingExchangeState) MarkInvestingDirty(price common.Hash) { func (s *lendingExchangeState) MarkInvestingDirty(price common.Hash) {
le.investingStatesDirty[price] = struct{}{} s.investingStatesDirty[price] = struct{}{}
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
} }
func (le *lendingExchangeState) MarkLendingItemDirty(lending common.Hash) { func (s *lendingExchangeState) MarkLendingItemDirty(lending common.Hash) {
le.lendingItemStatesDirty[lending] = struct{}{} s.lendingItemStatesDirty[lending] = struct{}{}
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
} }
func (le *lendingExchangeState) MarkLendingTradeDirty(tradeId common.Hash) { func (s *lendingExchangeState) MarkLendingTradeDirty(tradeId common.Hash) {
le.lendingTradeStatesDirty[tradeId] = struct{}{} s.lendingTradeStatesDirty[tradeId] = struct{}{}
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
} }
func (le *lendingExchangeState) MarkLiquidationTimeDirty(orderId common.Hash) { func (s *lendingExchangeState) MarkLiquidationTimeDirty(orderId common.Hash) {
le.liquidationTimestatesDirty[orderId] = struct{}{} s.liquidationTimestatesDirty[orderId] = struct{}{}
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
} }
func (le *lendingExchangeState) createBorrowingOrderList(db Database, price common.Hash) (newobj *itemListState) { func (s *lendingExchangeState) createBorrowingOrderList(db Database, price common.Hash) (newobj *itemListState) {
newobj = newItemListState(le.lendingBook, price, itemList{Volume: Zero}, le.MarkBorrowingDirty) newobj = newItemListState(s.lendingBook, price, itemList{Volume: Zero}, s.MarkBorrowingDirty)
le.borrowingStates[price] = newobj s.borrowingStates[price] = newobj
le.borrowingStatesDirty[price] = struct{}{} s.borrowingStatesDirty[price] = struct{}{}
data, err := rlp.EncodeToBytes(newobj) data, err := rlp.EncodeToBytes(newobj)
if err != nil { if err != nil {
panic(fmt.Errorf("can't encode order list object at %x: %v", price[:], err)) panic(fmt.Errorf("can't encode order list object at %x: %v", price[:], err))
} }
le.setError(le.getBorrowingTrie(db).TryUpdate(price[:], data)) s.setError(s.getBorrowingTrie(db).TryUpdate(price[:], data))
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.Hash()) s.onDirty(s.Hash())
le.onDirty = nil s.onDirty = nil
} }
return newobj return newobj
} }
func (le *lendingExchangeState) createLendingItem(db Database, orderId common.Hash, order LendingItem) (newobj *lendingItemState) { func (s *lendingExchangeState) createLendingItem(db Database, orderId common.Hash, order LendingItem) (newobj *lendingItemState) {
newobj = newLendinItemState(le.lendingBook, orderId, order, le.MarkLendingItemDirty) newobj = newLendinItemState(s.lendingBook, orderId, order, s.MarkLendingItemDirty)
orderIdHash := common.BigToHash(new(big.Int).SetUint64(order.LendingId)) orderIdHash := common.BigToHash(new(big.Int).SetUint64(order.LendingId))
le.lendingItemStates[orderIdHash] = newobj s.lendingItemStates[orderIdHash] = newobj
le.lendingItemStatesDirty[orderIdHash] = struct{}{} s.lendingItemStatesDirty[orderIdHash] = struct{}{}
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.lendingBook) s.onDirty(s.lendingBook)
le.onDirty = nil s.onDirty = nil
} }
return newobj return newobj
} }
func (le *lendingExchangeState) createLiquidationTime(db Database, time common.Hash) (newobj *liquidationTimeState) { func (s *lendingExchangeState) createLiquidationTime(db Database, time common.Hash) (newobj *liquidationTimeState) {
newobj = newLiquidationTimeState(time, le.lendingBook, itemList{Volume: Zero}, le.MarkLiquidationTimeDirty) newobj = newLiquidationTimeState(time, s.lendingBook, itemList{Volume: Zero}, s.MarkLiquidationTimeDirty)
le.liquidationTimeStates[time] = newobj s.liquidationTimeStates[time] = newobj
le.liquidationTimestatesDirty[time] = struct{}{} s.liquidationTimestatesDirty[time] = struct{}{}
data, err := rlp.EncodeToBytes(newobj) data, err := rlp.EncodeToBytes(newobj)
if err != nil { if err != nil {
panic(fmt.Errorf("can't encode liquidation time at %x: %v", time[:], err)) panic(fmt.Errorf("can't encode liquidation time at %x: %v", time[:], err))
} }
le.setError(le.getLiquidationTimeTrie(db).TryUpdate(time[:], data)) s.setError(s.getLiquidationTimeTrie(db).TryUpdate(time[:], data))
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.lendingBook) s.onDirty(s.lendingBook)
le.onDirty = nil s.onDirty = nil
} }
return newobj return newobj
} }
func (le *lendingExchangeState) insertLendingTrade(tradeId common.Hash, order LendingTrade) (newobj *lendingTradeState) { func (s *lendingExchangeState) insertLendingTrade(tradeId common.Hash, order LendingTrade) (newobj *lendingTradeState) {
newobj = newLendingTradeState(le.lendingBook, tradeId, order, le.MarkLendingTradeDirty) newobj = newLendingTradeState(s.lendingBook, tradeId, order, s.MarkLendingTradeDirty)
le.lendingTradeStates[tradeId] = newobj s.lendingTradeStates[tradeId] = newobj
le.lendingTradeStatesDirty[tradeId] = struct{}{} s.lendingTradeStatesDirty[tradeId] = struct{}{}
if le.onDirty != nil { if s.onDirty != nil {
le.onDirty(le.lendingBook) s.onDirty(s.lendingBook)
le.onDirty = nil s.onDirty = nil
} }
return newobj return newobj
} }

View file

@ -55,13 +55,13 @@ func newAccessList() *accessList {
} }
// Copy creates an independent copy of an accessList. // Copy creates an independent copy of an accessList.
func (a *accessList) Copy() *accessList { func (al *accessList) Copy() *accessList {
cp := newAccessList() cp := newAccessList()
for k, v := range a.addresses { for k, v := range al.addresses {
cp.addresses[k] = v cp.addresses[k] = v
} }
cp.slots = make([]map[common.Hash]struct{}, len(a.slots)) cp.slots = make([]map[common.Hash]struct{}, len(al.slots))
for i, slotMap := range a.slots { for i, slotMap := range al.slots {
newSlotmap := make(map[common.Hash]struct{}, len(slotMap)) newSlotmap := make(map[common.Hash]struct{}, len(slotMap))
for k := range slotMap { for k := range slotMap {
newSlotmap[k] = struct{}{} newSlotmap[k] = struct{}{}

View file

@ -392,11 +392,11 @@ func (s EIP155Signer) Hash(tx *Transaction) common.Hash {
// homestead rules. // homestead rules.
type HomesteadSigner struct{ FrontierSigner } type HomesteadSigner struct{ FrontierSigner }
func (s HomesteadSigner) ChainID() *big.Int { func (hs HomesteadSigner) ChainID() *big.Int {
return nil return nil
} }
func (s HomesteadSigner) Equal(s2 Signer) bool { func (hs HomesteadSigner) Equal(s2 Signer) bool {
_, ok := s2.(HomesteadSigner) _, ok := s2.(HomesteadSigner)
return ok return ok
} }
@ -417,11 +417,11 @@ func (hs HomesteadSigner) Sender(tx *Transaction) (common.Address, error) {
type FrontierSigner struct{} type FrontierSigner struct{}
func (s FrontierSigner) ChainID() *big.Int { func (fs FrontierSigner) ChainID() *big.Int {
return nil return nil
} }
func (s FrontierSigner) Equal(s2 Signer) bool { func (fs FrontierSigner) Equal(s2 Signer) bool {
_, ok := s2.(FrontierSigner) _, ok := s2.(FrontierSigner)
return ok return ok
} }

View file

@ -442,8 +442,8 @@ func (b *EthAPIBackend) CurrentHeader() *types.Header {
return b.eth.blockchain.CurrentHeader() return b.eth.blockchain.CurrentHeader()
} }
func (s *EthAPIBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int { func (b *EthAPIBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int {
header := s.eth.blockchain.GetHeaderByHash(hash) header := b.eth.blockchain.GetHeaderByHash(hash)
if header != nil { if header != nil {
data, err := os.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex())) data, err := os.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()))
if err == nil { if err == nil {

View file

@ -316,11 +316,11 @@ func PubkeyID(pub *ecdsa.PublicKey) NodeID {
// Pubkey returns the public key represented by the node ID. // Pubkey returns the public key represented by the node ID.
// It returns an error if the ID is not a point on the curve. // It returns an error if the ID is not a point on the curve.
func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) { func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) {
p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)} p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
half := len(id) / 2 half := len(n) / 2
p.X.SetBytes(id[:half]) p.X.SetBytes(n[:half])
p.Y.SetBytes(id[half:]) p.Y.SetBytes(n[half:])
if !p.Curve.IsOnCurve(p.X, p.Y) { if !p.Curve.IsOnCurve(p.X, p.Y) {
return nil, errors.New("invalid secp256k1 curve point") return nil, errors.New("invalid secp256k1 curve point")
} }

View file

@ -583,26 +583,26 @@ func (*preminedTestnet) ping(toid NodeID, toaddr *net.UDPAddr) error { return ni
// mine generates a testnet struct literal with nodes at // mine generates a testnet struct literal with nodes at
// various distances to the given target. // various distances to the given target.
func (n *preminedTestnet) mine(target NodeID) { func (tn *preminedTestnet) mine(target NodeID) {
n.target = target tn.target = target
n.targetSha = crypto.Keccak256Hash(n.target[:]) tn.targetSha = crypto.Keccak256Hash(tn.target[:])
found := 0 found := 0
for found < bucketSize*10 { for found < bucketSize*10 {
k := newkey() k := newkey()
id := PubkeyID(&k.PublicKey) id := PubkeyID(&k.PublicKey)
sha := crypto.Keccak256Hash(id[:]) sha := crypto.Keccak256Hash(id[:])
ld := logdist(n.targetSha, sha) ld := logdist(tn.targetSha, sha)
if len(n.dists[ld]) < bucketSize { if len(tn.dists[ld]) < bucketSize {
n.dists[ld] = append(n.dists[ld], id) tn.dists[ld] = append(tn.dists[ld], id)
fmt.Println("found ID with ld", ld) fmt.Println("found ID with ld", ld)
found++ found++
} }
} }
fmt.Println("&preminedTestnet{") fmt.Println("&preminedTestnet{")
fmt.Printf(" target: %#v,\n", n.target) fmt.Printf(" target: %#v,\n", tn.target)
fmt.Printf(" targetSha: %#v,\n", n.targetSha) fmt.Printf(" targetSha: %#v,\n", tn.targetSha)
fmt.Printf(" dists: [%d][]NodeID{\n", len(n.dists)) fmt.Printf(" dists: [%d][]NodeID{\n", len(tn.dists))
for ld, ns := range n.dists { for ld, ns := range tn.dists {
if len(ns) == 0 { if len(ns) == 0 {
continue continue
} }

View file

@ -336,26 +336,26 @@ func (*preminedTestnet) localAddr() *net.UDPAddr {
// mine generates a testnet struct literal with nodes at // mine generates a testnet struct literal with nodes at
// various distances to the given target. // various distances to the given target.
func (n *preminedTestnet) mine(target NodeID) { func (tn *preminedTestnet) mine(target NodeID) {
n.target = target tn.target = target
n.targetSha = crypto.Keccak256Hash(n.target[:]) tn.targetSha = crypto.Keccak256Hash(tn.target[:])
found := 0 found := 0
for found < bucketSize*10 { for found < bucketSize*10 {
k := newkey() k := newkey()
id := PubkeyID(&k.PublicKey) id := PubkeyID(&k.PublicKey)
sha := crypto.Keccak256Hash(id[:]) sha := crypto.Keccak256Hash(id[:])
ld := logdist(n.targetSha, sha) ld := logdist(tn.targetSha, sha)
if len(n.dists[ld]) < bucketSize { if len(tn.dists[ld]) < bucketSize {
n.dists[ld] = append(n.dists[ld], id) tn.dists[ld] = append(tn.dists[ld], id)
fmt.Println("found ID with ld", ld) fmt.Println("found ID with ld", ld)
found++ found++
} }
} }
fmt.Println("&preminedTestnet{") fmt.Println("&preminedTestnet{")
fmt.Printf(" target: %#v,\n", n.target) fmt.Printf(" target: %#v,\n", tn.target)
fmt.Printf(" targetSha: %#v,\n", n.targetSha) fmt.Printf(" targetSha: %#v,\n", tn.targetSha)
fmt.Printf(" dists: [%d][]NodeID{\n", len(n.dists)) fmt.Printf(" dists: [%d][]NodeID{\n", len(tn.dists))
for ld, ns := range n.dists { for ld, ns := range tn.dists {
if len(ns) == 0 { if len(ns) == 0 {
continue continue
} }

View file

@ -133,8 +133,8 @@ var incompleteNodeURL = regexp.MustCompile("(?i)^(?:enode://)?([0-9a-f]+)$")
// //
// For incomplete nodes, the designator must look like one of these // For incomplete nodes, the designator must look like one of these
// //
// enode://<hex node id> // enode://<hex node id>
// <hex node id> // <hex node id>
// //
// For complete nodes, the node ID is encoded in the username portion // For complete nodes, the node ID is encoded in the username portion
// of the URL, separated from the host by an @ sign. The hostname can // of the URL, separated from the host by an @ sign. The hostname can
@ -147,7 +147,7 @@ var incompleteNodeURL = regexp.MustCompile("(?i)^(?:enode://)?([0-9a-f]+)$")
// a node with IP address 10.3.58.6, TCP listening port 30303 // a node with IP address 10.3.58.6, TCP listening port 30303
// and UDP discovery port 30301. // and UDP discovery port 30301.
// //
// enode://<hex node id>@10.3.58.6:30303?discport=30301 // enode://<hex node id>@10.3.58.6:30303?discport=30301
func ParseNode(rawurl string) (*Node, error) { func ParseNode(rawurl string) (*Node, error) {
if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil { if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil {
id, err := HexID(m[1]) id, err := HexID(m[1])
@ -315,19 +315,19 @@ func PubkeyID(pub *ecdsa.PublicKey) NodeID {
// Pubkey returns the public key represented by the node ID. // Pubkey returns the public key represented by the node ID.
// It returns an error if the ID is not a point on the curve. // It returns an error if the ID is not a point on the curve.
func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) { func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) {
p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)} p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
half := len(id) / 2 half := len(n) / 2
p.X.SetBytes(id[:half]) p.X.SetBytes(n[:half])
p.Y.SetBytes(id[half:]) p.Y.SetBytes(n[half:])
if !p.Curve.IsOnCurve(p.X, p.Y) { if !p.Curve.IsOnCurve(p.X, p.Y) {
return nil, errors.New("id is invalid secp256k1 curve point") return nil, errors.New("id is invalid secp256k1 curve point")
} }
return p, nil return p, nil
} }
func (id NodeID) mustPubkey() ecdsa.PublicKey { func (n NodeID) mustPubkey() ecdsa.PublicKey {
pk, err := id.Pubkey() pk, err := n.Pubkey()
if err != nil { if err != nil {
panic(err) panic(err)
} }

View file

@ -305,8 +305,8 @@ func (s ticketRefByWaitTime) Len() int {
return len(s) return len(s)
} }
func (r ticketRef) waitTime() mclock.AbsTime { func (ref ticketRef) waitTime() mclock.AbsTime {
return r.t.regTime[r.idx] - r.t.issueTime return ref.t.regTime[ref.idx] - ref.t.issueTime
} }
// Less reports whether the element with // Less reports whether the element with

View file

@ -90,70 +90,70 @@ func newTopicTable(db *nodeDB, self *Node) *topicTable {
} }
} }
func (t *topicTable) getOrNewTopic(topic Topic) *topicInfo { func (topictab *topicTable) getOrNewTopic(topic Topic) *topicInfo {
ti := t.topics[topic] ti := topictab.topics[topic]
if ti == nil { if ti == nil {
rqItem := &topicRequestQueueItem{ rqItem := &topicRequestQueueItem{
topic: topic, topic: topic,
priority: t.requestCnt, priority: topictab.requestCnt,
} }
ti = &topicInfo{ ti = &topicInfo{
entries: make(map[uint64]*topicEntry), entries: make(map[uint64]*topicEntry),
rqItem: rqItem, rqItem: rqItem,
} }
t.topics[topic] = ti topictab.topics[topic] = ti
heap.Push(&t.requested, rqItem) heap.Push(&topictab.requested, rqItem)
} }
return ti return ti
} }
func (t *topicTable) checkDeleteTopic(topic Topic) { func (topictab *topicTable) checkDeleteTopic(topic Topic) {
ti := t.topics[topic] ti := topictab.topics[topic]
if ti == nil { if ti == nil {
return return
} }
if len(ti.entries) == 0 && ti.wcl.hasMinimumWaitPeriod() { if len(ti.entries) == 0 && ti.wcl.hasMinimumWaitPeriod() {
delete(t.topics, topic) delete(topictab.topics, topic)
heap.Remove(&t.requested, ti.rqItem.index) heap.Remove(&topictab.requested, ti.rqItem.index)
} }
} }
func (t *topicTable) getOrNewNode(node *Node) *nodeInfo { func (topictab *topicTable) getOrNewNode(node *Node) *nodeInfo {
n := t.nodes[node] n := topictab.nodes[node]
if n == nil { if n == nil {
//fmt.Printf("newNode %016x %016x\n", t.self.sha[:8], node.sha[:8]) //fmt.Printf("newNode %016x %016x\n", t.self.sha[:8], node.sha[:8])
var issued, used uint32 var issued, used uint32
if t.db != nil { if topictab.db != nil {
issued, used = t.db.fetchTopicRegTickets(node.ID) issued, used = topictab.db.fetchTopicRegTickets(node.ID)
} }
n = &nodeInfo{ n = &nodeInfo{
entries: make(map[Topic]*topicEntry), entries: make(map[Topic]*topicEntry),
lastIssuedTicket: issued, lastIssuedTicket: issued,
lastUsedTicket: used, lastUsedTicket: used,
} }
t.nodes[node] = n topictab.nodes[node] = n
} }
return n return n
} }
func (t *topicTable) checkDeleteNode(node *Node) { func (topictab *topicTable) checkDeleteNode(node *Node) {
if n, ok := t.nodes[node]; ok && len(n.entries) == 0 && n.noRegUntil < mclock.Now() { if n, ok := topictab.nodes[node]; ok && len(n.entries) == 0 && n.noRegUntil < mclock.Now() {
//fmt.Printf("deleteNode %016x %016x\n", t.self.sha[:8], node.sha[:8]) //fmt.Printf("deleteNode %016x %016x\n", t.self.sha[:8], node.sha[:8])
delete(t.nodes, node) delete(topictab.nodes, node)
} }
} }
func (t *topicTable) storeTicketCounters(node *Node) { func (topictab *topicTable) storeTicketCounters(node *Node) {
n := t.getOrNewNode(node) n := topictab.getOrNewNode(node)
if t.db != nil { if topictab.db != nil {
t.db.updateTopicRegTickets(node.ID, n.lastIssuedTicket, n.lastUsedTicket) topictab.db.updateTopicRegTickets(node.ID, n.lastIssuedTicket, n.lastUsedTicket)
} }
} }
func (t *topicTable) getEntries(topic Topic) []*Node { func (topictab *topicTable) getEntries(topic Topic) []*Node {
t.collectGarbage() topictab.collectGarbage()
te := t.topics[topic] te := topictab.topics[topic]
if te == nil { if te == nil {
return nil return nil
} }
@ -163,29 +163,29 @@ func (t *topicTable) getEntries(topic Topic) []*Node {
nodes[i] = e.node nodes[i] = e.node
i++ i++
} }
t.requestCnt++ topictab.requestCnt++
t.requested.update(te.rqItem, t.requestCnt) topictab.requested.update(te.rqItem, topictab.requestCnt)
return nodes return nodes
} }
func (t *topicTable) addEntry(node *Node, topic Topic) { func (topictab *topicTable) addEntry(node *Node, topic Topic) {
n := t.getOrNewNode(node) n := topictab.getOrNewNode(node)
// clear previous entries by the same node // clear previous entries by the same node
for _, e := range n.entries { for _, e := range n.entries {
t.deleteEntry(e) topictab.deleteEntry(e)
} }
// *** // ***
n = t.getOrNewNode(node) n = topictab.getOrNewNode(node)
tm := mclock.Now() tm := mclock.Now()
te := t.getOrNewTopic(topic) te := topictab.getOrNewTopic(topic)
if len(te.entries) == maxEntriesPerTopic { if len(te.entries) == maxEntriesPerTopic {
t.deleteEntry(te.getFifoTail()) topictab.deleteEntry(te.getFifoTail())
} }
if t.globalEntries == maxEntries { if topictab.globalEntries == maxEntries {
t.deleteEntry(t.leastRequested()) // not empty, no need to check for nil topictab.deleteEntry(topictab.leastRequested()) // not empty, no need to check for nil
} }
fifoIdx := te.fifoHead fifoIdx := te.fifoHead
@ -197,50 +197,50 @@ func (t *topicTable) addEntry(node *Node, topic Topic) {
expire: tm.Add(fallbackRegistrationExpiry), expire: tm.Add(fallbackRegistrationExpiry),
} }
if printTestImgLogs { if printTestImgLogs {
fmt.Printf("*+ %d %v %016x %016x\n", tm/1000000, topic, t.self.sha[:8], node.sha[:8]) fmt.Printf("*+ %d %v %016x %016x\n", tm/1000000, topic, topictab.self.sha[:8], node.sha[:8])
} }
te.entries[fifoIdx] = entry te.entries[fifoIdx] = entry
n.entries[topic] = entry n.entries[topic] = entry
t.globalEntries++ topictab.globalEntries++
te.wcl.registered(tm) te.wcl.registered(tm)
} }
// removes least requested element from the fifo // removes least requested element from the fifo
func (t *topicTable) leastRequested() *topicEntry { func (topictab *topicTable) leastRequested() *topicEntry {
for t.requested.Len() > 0 && t.topics[t.requested[0].topic] == nil { for topictab.requested.Len() > 0 && topictab.topics[topictab.requested[0].topic] == nil {
heap.Pop(&t.requested) heap.Pop(&topictab.requested)
} }
if t.requested.Len() == 0 { if topictab.requested.Len() == 0 {
return nil return nil
} }
return t.topics[t.requested[0].topic].getFifoTail() return topictab.topics[topictab.requested[0].topic].getFifoTail()
} }
// entry should exist // entry should exist
func (t *topicTable) deleteEntry(e *topicEntry) { func (topictab *topicTable) deleteEntry(e *topicEntry) {
if printTestImgLogs { if printTestImgLogs {
fmt.Printf("*- %d %v %016x %016x\n", mclock.Now()/1000000, e.topic, t.self.sha[:8], e.node.sha[:8]) fmt.Printf("*- %d %v %016x %016x\n", mclock.Now()/1000000, e.topic, topictab.self.sha[:8], e.node.sha[:8])
} }
ne := t.nodes[e.node].entries ne := topictab.nodes[e.node].entries
delete(ne, e.topic) delete(ne, e.topic)
if len(ne) == 0 { if len(ne) == 0 {
t.checkDeleteNode(e.node) topictab.checkDeleteNode(e.node)
} }
te := t.topics[e.topic] te := topictab.topics[e.topic]
delete(te.entries, e.fifoIdx) delete(te.entries, e.fifoIdx)
if len(te.entries) == 0 { if len(te.entries) == 0 {
t.checkDeleteTopic(e.topic) topictab.checkDeleteTopic(e.topic)
} }
t.globalEntries-- topictab.globalEntries--
} }
// It is assumed that topics and waitPeriods have the same length. // It is assumed that topics and waitPeriods have the same length.
func (t *topicTable) useTicket(node *Node, serialNo uint32, topics []Topic, idx int, issueTime uint64, waitPeriods []uint32) (registered bool) { func (topictab *topicTable) useTicket(node *Node, serialNo uint32, topics []Topic, idx int, issueTime uint64, waitPeriods []uint32) (registered bool) {
log.Trace("Using discovery ticket", "serial", serialNo, "topics", topics, "waits", waitPeriods) log.Trace("Using discovery ticket", "serial", serialNo, "topics", topics, "waits", waitPeriods)
//fmt.Println("useTicket", serialNo, topics, waitPeriods) //fmt.Println("useTicket", serialNo, topics, waitPeriods)
t.collectGarbage() topictab.collectGarbage()
n := t.getOrNewNode(node) n := topictab.getOrNewNode(node)
if serialNo < n.lastUsedTicket { if serialNo < n.lastUsedTicket {
return false return false
} }
@ -252,7 +252,7 @@ func (t *topicTable) useTicket(node *Node, serialNo uint32, topics []Topic, idx
if serialNo != n.lastUsedTicket { if serialNo != n.lastUsedTicket {
n.lastUsedTicket = serialNo n.lastUsedTicket = serialNo
n.noRegUntil = tm.Add(noRegTimeout()) n.noRegUntil = tm.Add(noRegTimeout())
t.storeTicketCounters(node) topictab.storeTicketCounters(node)
} }
currTime := uint64(tm / mclock.AbsTime(time.Second)) currTime := uint64(tm / mclock.AbsTime(time.Second))
@ -260,7 +260,7 @@ func (t *topicTable) useTicket(node *Node, serialNo uint32, topics []Topic, idx
relTime := int64(currTime - regTime) relTime := int64(currTime - regTime)
if relTime >= -1 && relTime <= regTimeWindow+1 { // give clients a little security margin on both ends if relTime >= -1 && relTime <= regTimeWindow+1 { // give clients a little security margin on both ends
if e := n.entries[topics[idx]]; e == nil { if e := n.entries[topics[idx]]; e == nil {
t.addEntry(node, topics[idx]) topictab.addEntry(node, topics[idx])
} else { } else {
// if there is an active entry, don't move to the front of the FIFO but prolong expire time // if there is an active entry, don't move to the front of the FIFO but prolong expire time
e.expire = tm.Add(fallbackRegistrationExpiry) e.expire = tm.Add(fallbackRegistrationExpiry)
@ -300,25 +300,25 @@ func (topictab *topicTable) getTicket(node *Node, topics []Topic) *ticket {
const gcInterval = time.Minute const gcInterval = time.Minute
func (t *topicTable) collectGarbage() { func (topictab *topicTable) collectGarbage() {
tm := mclock.Now() tm := mclock.Now()
if time.Duration(tm-t.lastGarbageCollection) < gcInterval { if time.Duration(tm-topictab.lastGarbageCollection) < gcInterval {
return return
} }
t.lastGarbageCollection = tm topictab.lastGarbageCollection = tm
for node, n := range t.nodes { for node, n := range topictab.nodes {
for _, e := range n.entries { for _, e := range n.entries {
if e.expire <= tm { if e.expire <= tm {
t.deleteEntry(e) topictab.deleteEntry(e)
} }
} }
t.checkDeleteNode(node) topictab.checkDeleteNode(node)
} }
for topic := range t.topics { for topic := range topictab.topics {
t.checkDeleteTopic(topic) topictab.checkDeleteTopic(topic)
} }
} }

View file

@ -583,42 +583,42 @@ func (c *XDPoSConfig) BlockConsensusVersion(num *big.Int, extraByte []byte, extr
return ConsensusEngineVersion1 return ConsensusEngineVersion1
} }
func (v *V2) UpdateConfig(round uint64) { func (v2 *V2) UpdateConfig(round uint64) {
v.lock.Lock() v2.lock.Lock()
defer v.lock.Unlock() defer v2.lock.Unlock()
var index uint64 var index uint64
//find the right config //find the right config
for i := range v.configIndex { for i := range v2.configIndex {
if v.configIndex[i] <= round { if v2.configIndex[i] <= round {
index = v.configIndex[i] index = v2.configIndex[i]
break break
} }
} }
// update to current config // update to current config
log.Info("[updateV2Config] Update config", "index", index, "round", round, "SwitchRound", v.AllConfigs[index].SwitchRound) log.Info("[updateV2Config] Update config", "index", index, "round", round, "SwitchRound", v2.AllConfigs[index].SwitchRound)
v.CurrentConfig = v.AllConfigs[index] v2.CurrentConfig = v2.AllConfigs[index]
} }
func (v *V2) Config(round uint64) *V2Config { func (v2 *V2) Config(round uint64) *V2Config {
configRound := round configRound := round
var index uint64 var index uint64
//find the right config //find the right config
for i := range v.configIndex { for i := range v2.configIndex {
if v.configIndex[i] <= configRound { if v2.configIndex[i] <= configRound {
index = v.configIndex[i] index = v2.configIndex[i]
break break
} }
} }
return v.AllConfigs[index] return v2.AllConfigs[index]
} }
func (v *V2) BuildConfigIndex() { func (v2 *V2) BuildConfigIndex() {
var list []uint64 var list []uint64
for i := range v.AllConfigs { for i := range v2.AllConfigs {
list = append(list, i) list = append(list, i)
} }
@ -632,11 +632,11 @@ func (v *V2) BuildConfigIndex() {
} }
} }
log.Info("[BuildConfigIndex] config list", "list", list) log.Info("[BuildConfigIndex] config list", "list", list)
v.configIndex = list v2.configIndex = list
} }
func (v *V2) ConfigIndex() []uint64 { func (v2 *V2) ConfigIndex() []uint64 {
return v.configIndex return v2.configIndex
} }
// Description returns a human-readable description of ChainConfig. // Description returns a human-readable description of ChainConfig.