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)
}
func (XDCX *XDCX) GetEmptyTradingState() (*tradingstate.TradingStateDB, error) {
return tradingstate.New(tradingstate.EmptyRoot, XDCX.StateCache)
func (XDCx *XDCX) GetEmptyTradingState() (*tradingstate.TradingStateDB, error) {
return tradingstate.New(tradingstate.EmptyRoot, XDCx.StateCache)
}
func (XDCx *XDCX) GetStateCache() tradingstate.Database {

View file

@ -306,26 +306,26 @@ func (s *stateLendingBook) DumpOrderList(db Database) DumpOrderList {
return mapResult
}
func (l *liquidationPriceState) DumpLendingBook(db Database) (DumpLendingBook, error) {
result := DumpLendingBook{Volume: l.Volume(), LendingBooks: map[common.Hash]DumpOrderList{}}
it := trie.NewIterator(l.getTrie(db).NodeIterator(nil))
func (s *liquidationPriceState) DumpLendingBook(db Database) (DumpLendingBook, error) {
result := DumpLendingBook{Volume: s.Volume(), LendingBooks: map[common.Hash]DumpOrderList{}}
it := trie.NewIterator(s.getTrie(db).NodeIterator(nil))
for it.Next() {
lendingBook := common.BytesToHash(it.Key)
if lendingBook.IsZero() {
continue
}
if _, exist := l.stateLendingBooks[lendingBook]; exist {
if _, exist := s.stateLendingBooks[lendingBook]; exist {
continue
} else {
var data orderList
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)
}
}
for lendingBook, stateLendingBook := range l.stateLendingBooks {
for lendingBook, stateLendingBook := range s.stateLendingBooks {
if !lendingBook.IsZero() {
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.
func (l *liquidationPriceState) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, l.data)
func (s *liquidationPriceState) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, s.data)
}
// setError remembers the first non-nil error it is called with.
func (l *liquidationPriceState) setError(err error) {
if l.dbErr == nil {
l.dbErr = err
func (s *liquidationPriceState) setError(err error) {
if s.dbErr == nil {
s.dbErr = err
}
}
func (l *liquidationPriceState) MarkStateLendingBookDirty(price common.Hash) {
l.stateLendingBooksDirty[price] = struct{}{}
if l.onDirty != nil {
l.onDirty(l.liquidationPrice)
l.onDirty = nil
func (s *liquidationPriceState) MarkStateLendingBookDirty(price common.Hash) {
s.stateLendingBooksDirty[price] = struct{}{}
if s.onDirty != nil {
s.onDirty(s.liquidationPrice)
s.onDirty = nil
}
}
func (l *liquidationPriceState) createLendingBook(db Database, lendingBook common.Hash) (newobj *stateLendingBook) {
newobj = newStateLendingBook(l.orderBook, l.liquidationPrice, lendingBook, orderList{Volume: Zero}, l.MarkStateLendingBookDirty)
l.stateLendingBooks[lendingBook] = newobj
l.stateLendingBooksDirty[lendingBook] = struct{}{}
if l.onDirty != nil {
l.onDirty(l.liquidationPrice)
l.onDirty = nil
func (s *liquidationPriceState) createLendingBook(db Database, lendingBook common.Hash) (newobj *stateLendingBook) {
newobj = newStateLendingBook(s.orderBook, s.liquidationPrice, lendingBook, orderList{Volume: Zero}, s.MarkStateLendingBookDirty)
s.stateLendingBooks[lendingBook] = newobj
s.stateLendingBooksDirty[lendingBook] = struct{}{}
if s.onDirty != nil {
s.onDirty(s.liquidationPrice)
s.onDirty = nil
}
return newobj
}
func (l *liquidationPriceState) getTrie(db Database) Trie {
if l.trie == nil {
func (s *liquidationPriceState) getTrie(db Database) Trie {
if s.trie == nil {
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 {
l.trie, _ = db.OpenStorageTrie(l.liquidationPrice, types.EmptyRootHash)
l.setError(fmt.Errorf("can't create storage trie: %v", err))
s.trie, _ = db.OpenStorageTrie(s.liquidationPrice, types.EmptyRootHash)
s.setError(fmt.Errorf("can't create storage trie: %v", err))
}
}
return l.trie
return s.trie
}
func (l *liquidationPriceState) updateTrie(db Database) Trie {
tr := l.getTrie(db)
for lendingId, stateObject := range l.stateLendingBooks {
delete(l.stateLendingBooksDirty, lendingId)
func (s *liquidationPriceState) updateTrie(db Database) Trie {
tr := s.getTrie(db)
for lendingId, stateObject := range s.stateLendingBooks {
delete(s.stateLendingBooksDirty, lendingId)
if stateObject.empty() {
l.setError(tr.TryDelete(lendingId[:]))
s.setError(tr.TryDelete(lendingId[:]))
continue
}
err := stateObject.updateRoot(db)
@ -126,17 +126,17 @@ func (l *liquidationPriceState) updateTrie(db Database) Trie {
// Encoding []byte cannot fail, ok to ignore the error.
v, _ := rlp.EncodeToBytes(stateObject)
l.setError(tr.TryUpdate(lendingId[:], v))
s.setError(tr.TryUpdate(lendingId[:], v))
}
return tr
}
func (l *liquidationPriceState) updateRoot(db Database) error {
l.updateTrie(db)
if l.dbErr != nil {
return l.dbErr
func (s *liquidationPriceState) updateRoot(db Database) error {
s.updateTrie(db)
if s.dbErr != nil {
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
if err := rlp.DecodeBytes(leaf, &orderList); err != nil {
return nil
@ -147,57 +147,57 @@ func (l *liquidationPriceState) updateRoot(db Database) error {
return nil
})
if err == nil {
l.data.Root = root
s.data.Root = root
}
return err
}
func (l *liquidationPriceState) deepCopy(db *TradingStateDB, onDirty func(liquidationPrice common.Hash)) *liquidationPriceState {
stateOrderList := newLiquidationPriceState(db, l.orderBook, l.liquidationPrice, l.data, onDirty)
if l.trie != nil {
stateOrderList.trie = db.db.CopyTrie(l.trie)
func (s *liquidationPriceState) deepCopy(db *TradingStateDB, onDirty func(liquidationPrice common.Hash)) *liquidationPriceState {
stateOrderList := newLiquidationPriceState(db, s.orderBook, s.liquidationPrice, s.data, onDirty)
if s.trie != nil {
stateOrderList.trie = db.db.CopyTrie(s.trie)
}
for key, value := range l.stateLendingBooks {
stateOrderList.stateLendingBooks[key] = value.deepCopy(db, l.MarkStateLendingBookDirty)
for key, value := range s.stateLendingBooks {
stateOrderList.stateLendingBooks[key] = value.deepCopy(db, s.MarkStateLendingBookDirty)
}
for key, value := range l.stateLendingBooksDirty {
for key, value := range s.stateLendingBooksDirty {
stateOrderList.stateLendingBooksDirty[key] = value
}
return stateOrderList
}
// 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.
if obj := l.stateLendingBooks[lendingBook]; obj != nil {
if obj := s.stateLendingBooks[lendingBook]; obj != nil {
return obj
}
// Load the object from the database.
enc, err := l.getTrie(db).TryGet(lendingBook[:])
enc, err := s.getTrie(db).TryGet(lendingBook[:])
if len(enc) == 0 {
l.setError(err)
s.setError(err)
return nil
}
var data orderList
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
}
// Insert into the live set.
obj := newStateLendingBook(l.orderBook, l.liquidationPrice, lendingBook, data, l.MarkStateLendingBookDirty)
l.stateLendingBooks[lendingBook] = obj
obj := newStateLendingBook(s.orderBook, s.liquidationPrice, lendingBook, data, s.MarkStateLendingBookDirty)
s.stateLendingBooks[lendingBook] = 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{}
lendingBookTrie := l.getTrie(db)
lendingBookTrie := s.getTrie(db)
if lendingBookTrie == nil {
return liquidationData
}
lendingBooks := []common.Hash{}
for id, stateLendingBook := range l.stateLendingBooks {
for id, stateLendingBook := range s.stateLendingBooks {
if !stateLendingBook.empty() {
lendingBooks = append(lendingBooks, id)
}
@ -205,13 +205,13 @@ func (l *liquidationPriceState) getAllLiquidationData(db Database) map[common.Ha
lendingBookListIt := trie.NewIterator(lendingBookTrie.NodeIterator(nil))
for lendingBookListIt.Next() {
id := common.BytesToHash(lendingBookListIt.Key)
if _, exist := l.stateLendingBooks[id]; exist {
if _, exist := s.stateLendingBooks[id]; exist {
continue
}
lendingBooks = append(lendingBooks, id)
}
for _, lendingBook := range lendingBooks {
stateLendingBook := l.getStateLendingBook(db, lendingBook)
stateLendingBook := s.getStateLendingBook(db, lendingBook)
if stateLendingBook != nil {
liquidationData[lendingBook] = stateLendingBook.getAllTradeIds(db)
}
@ -219,22 +219,22 @@ func (l *liquidationPriceState) getAllLiquidationData(db Database) map[common.Ha
return liquidationData
}
func (l *liquidationPriceState) AddVolume(amount *big.Int) {
l.setVolume(new(big.Int).Add(l.data.Volume, amount))
func (s *liquidationPriceState) AddVolume(amount *big.Int) {
s.setVolume(new(big.Int).Add(s.data.Volume, amount))
}
func (c *liquidationPriceState) subVolume(amount *big.Int) {
c.setVolume(new(big.Int).Sub(c.data.Volume, amount))
func (s *liquidationPriceState) subVolume(amount *big.Int) {
s.setVolume(new(big.Int).Sub(s.data.Volume, amount))
}
func (l *liquidationPriceState) setVolume(volume *big.Int) {
l.data.Volume = volume
if l.onDirty != nil {
l.onDirty(l.liquidationPrice)
l.onDirty = nil
func (s *liquidationPriceState) setVolume(volume *big.Int) {
s.data.Volume = volume
if s.onDirty != nil {
s.onDirty(s.liquidationPrice)
s.onDirty = nil
}
}
func (l *liquidationPriceState) Volume() *big.Int {
return l.data.Volume
func (s *liquidationPriceState) Volume() *big.Int {
return s.data.Volume
}

View file

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

View file

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

View file

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

View file

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

View file

@ -442,8 +442,8 @@ func (b *EthAPIBackend) CurrentHeader() *types.Header {
return b.eth.blockchain.CurrentHeader()
}
func (s *EthAPIBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int {
header := s.eth.blockchain.GetHeaderByHash(hash)
func (b *EthAPIBackend) GetRewardByHash(hash common.Hash) map[string]map[string]map[string]*big.Int {
header := b.eth.blockchain.GetHeaderByHash(hash)
if header != nil {
data, err := os.ReadFile(filepath.Join(common.StoreRewardFolder, header.Number.String()+"."+header.Hash().Hex()))
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.
// 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)}
half := len(id) / 2
p.X.SetBytes(id[:half])
p.Y.SetBytes(id[half:])
half := len(n) / 2
p.X.SetBytes(n[:half])
p.Y.SetBytes(n[half:])
if !p.Curve.IsOnCurve(p.X, p.Y) {
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
// various distances to the given target.
func (n *preminedTestnet) mine(target NodeID) {
n.target = target
n.targetSha = crypto.Keccak256Hash(n.target[:])
func (tn *preminedTestnet) mine(target NodeID) {
tn.target = target
tn.targetSha = crypto.Keccak256Hash(tn.target[:])
found := 0
for found < bucketSize*10 {
k := newkey()
id := PubkeyID(&k.PublicKey)
sha := crypto.Keccak256Hash(id[:])
ld := logdist(n.targetSha, sha)
if len(n.dists[ld]) < bucketSize {
n.dists[ld] = append(n.dists[ld], id)
ld := logdist(tn.targetSha, sha)
if len(tn.dists[ld]) < bucketSize {
tn.dists[ld] = append(tn.dists[ld], id)
fmt.Println("found ID with ld", ld)
found++
}
}
fmt.Println("&preminedTestnet{")
fmt.Printf(" target: %#v,\n", n.target)
fmt.Printf(" targetSha: %#v,\n", n.targetSha)
fmt.Printf(" dists: [%d][]NodeID{\n", len(n.dists))
for ld, ns := range n.dists {
fmt.Printf(" target: %#v,\n", tn.target)
fmt.Printf(" targetSha: %#v,\n", tn.targetSha)
fmt.Printf(" dists: [%d][]NodeID{\n", len(tn.dists))
for ld, ns := range tn.dists {
if len(ns) == 0 {
continue
}

View file

@ -336,26 +336,26 @@ func (*preminedTestnet) localAddr() *net.UDPAddr {
// mine generates a testnet struct literal with nodes at
// various distances to the given target.
func (n *preminedTestnet) mine(target NodeID) {
n.target = target
n.targetSha = crypto.Keccak256Hash(n.target[:])
func (tn *preminedTestnet) mine(target NodeID) {
tn.target = target
tn.targetSha = crypto.Keccak256Hash(tn.target[:])
found := 0
for found < bucketSize*10 {
k := newkey()
id := PubkeyID(&k.PublicKey)
sha := crypto.Keccak256Hash(id[:])
ld := logdist(n.targetSha, sha)
if len(n.dists[ld]) < bucketSize {
n.dists[ld] = append(n.dists[ld], id)
ld := logdist(tn.targetSha, sha)
if len(tn.dists[ld]) < bucketSize {
tn.dists[ld] = append(tn.dists[ld], id)
fmt.Println("found ID with ld", ld)
found++
}
}
fmt.Println("&preminedTestnet{")
fmt.Printf(" target: %#v,\n", n.target)
fmt.Printf(" targetSha: %#v,\n", n.targetSha)
fmt.Printf(" dists: [%d][]NodeID{\n", len(n.dists))
for ld, ns := range n.dists {
fmt.Printf(" target: %#v,\n", tn.target)
fmt.Printf(" targetSha: %#v,\n", tn.targetSha)
fmt.Printf(" dists: [%d][]NodeID{\n", len(tn.dists))
for ld, ns := range tn.dists {
if len(ns) == 0 {
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
//
// enode://<hex node id>
// <hex node id>
// enode://<hex node id>
// <hex node id>
//
// 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
@ -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
// 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) {
if m := incompleteNodeURL.FindStringSubmatch(rawurl); m != nil {
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.
// 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)}
half := len(id) / 2
p.X.SetBytes(id[:half])
p.Y.SetBytes(id[half:])
half := len(n) / 2
p.X.SetBytes(n[:half])
p.Y.SetBytes(n[half:])
if !p.Curve.IsOnCurve(p.X, p.Y) {
return nil, errors.New("id is invalid secp256k1 curve point")
}
return p, nil
}
func (id NodeID) mustPubkey() ecdsa.PublicKey {
pk, err := id.Pubkey()
func (n NodeID) mustPubkey() ecdsa.PublicKey {
pk, err := n.Pubkey()
if err != nil {
panic(err)
}

View file

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

View file

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