common: improve documentation comments (#16701)

This commit is contained in:
Daniel Liu 2024-12-18 17:50:26 +08:00
parent 43ad328487
commit 89c51c5e69
21 changed files with 118 additions and 180 deletions

View file

@ -525,7 +525,7 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *tradingsta
matchingFee = new(big.Int).Add(matchingFee, common.RelayerFee)
matchingFee = new(big.Int).Add(matchingFee, common.RelayerFee)
if common.EmptyHash(takerExOwner.Hash()) || common.EmptyHash(makerExOwner.Hash()) {
if takerExOwner.Hash().IsZero() || makerExOwner.Hash().IsZero() {
return fmt.Errorf("empty echange owner: taker: %v , maker : %v", takerExOwner, makerExOwner)
}
mapBalances := map[common.Address]map[common.Address]*big.Int{}

View file

@ -56,7 +56,7 @@ func (t *TradingStateDB) DumpAskTrie(orderBook common.Hash) (map[*big.Int]DumpOr
it := trie.NewIterator(exhangeObject.getAsksTrie(t.db).NodeIterator(nil))
for it.Next() {
priceHash := common.BytesToHash(it.Key)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
continue
}
price := new(big.Int).SetBytes(priceHash.Bytes())
@ -99,7 +99,7 @@ func (t *TradingStateDB) DumpBidTrie(orderBook common.Hash) (map[*big.Int]DumpOr
it := trie.NewIterator(exhangeObject.getBidsTrie(t.db).NodeIterator(nil))
for it.Next() {
priceHash := common.BytesToHash(it.Key)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
continue
}
price := new(big.Int).SetBytes(priceHash.Bytes())
@ -142,7 +142,7 @@ func (t *TradingStateDB) GetBids(orderBook common.Hash) (map[*big.Int]*big.Int,
it := trie.NewIterator(exhangeObject.getBidsTrie(t.db).NodeIterator(nil))
for it.Next() {
priceHash := common.BytesToHash(it.Key)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
continue
}
price := new(big.Int).SetBytes(priceHash.Bytes())
@ -185,7 +185,7 @@ func (t *TradingStateDB) GetAsks(orderBook common.Hash) (map[*big.Int]*big.Int,
it := trie.NewIterator(exhangeObject.getAsksTrie(t.db).NodeIterator(nil))
for it.Next() {
priceHash := common.BytesToHash(it.Key)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
continue
}
price := new(big.Int).SetBytes(priceHash.Bytes())
@ -224,7 +224,7 @@ func (s *stateOrderList) DumpOrderList(db Database) DumpOrderList {
orderListIt := trie.NewIterator(s.getTrie(db).NodeIterator(nil))
for orderListIt.Next() {
keyHash := common.BytesToHash(orderListIt.Key)
if common.EmptyHash(keyHash) {
if keyHash.IsZero() {
continue
}
if _, exist := s.cachedStorage[keyHash]; exist {
@ -235,7 +235,7 @@ func (s *stateOrderList) DumpOrderList(db Database) DumpOrderList {
}
}
for key, value := range s.cachedStorage {
if !common.EmptyHash(value) {
if !value.IsZero() {
mapResult.Orders[new(big.Int).SetBytes(key.Bytes())] = new(big.Int).SetBytes(value.Bytes())
}
}
@ -277,7 +277,7 @@ func (s *stateLendingBook) DumpOrderList(db Database) DumpOrderList {
orderListIt := trie.NewIterator(s.getTrie(db).NodeIterator(nil))
for orderListIt.Next() {
keyHash := common.BytesToHash(orderListIt.Key)
if common.EmptyHash(keyHash) {
if keyHash.IsZero() {
continue
}
if _, exist := s.cachedStorage[keyHash]; exist {
@ -288,7 +288,7 @@ func (s *stateLendingBook) DumpOrderList(db Database) DumpOrderList {
}
}
for key, value := range s.cachedStorage {
if !common.EmptyHash(value) {
if !value.IsZero() {
mapResult.Orders[new(big.Int).SetBytes(key.Bytes())] = new(big.Int).SetBytes(value.Bytes())
}
}
@ -311,7 +311,7 @@ func (l *liquidationPriceState) DumpLendingBook(db Database) (DumpLendingBook, e
it := trie.NewIterator(l.getTrie(db).NodeIterator(nil))
for it.Next() {
lendingBook := common.BytesToHash(it.Key)
if common.EmptyHash(lendingBook) {
if lendingBook.IsZero() {
continue
}
if _, exist := l.stateLendingBooks[lendingBook]; exist {
@ -326,7 +326,7 @@ func (l *liquidationPriceState) DumpLendingBook(db Database) (DumpLendingBook, e
}
}
for lendingBook, stateLendingBook := range l.stateLendingBooks {
if !common.EmptyHash(lendingBook) {
if !lendingBook.IsZero() {
result.LendingBooks[lendingBook] = stateLendingBook.DumpOrderList(db)
}
}
@ -342,7 +342,7 @@ func (t *TradingStateDB) DumpLiquidationPriceTrie(orderBook common.Hash) (map[*b
it := trie.NewIterator(exhangeObject.getLiquidationPriceTrie(t.db).NodeIterator(nil))
for it.Next() {
priceHash := common.BytesToHash(it.Key)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
continue
}
price := new(big.Int).SetBytes(priceHash.Bytes())

View file

@ -118,7 +118,7 @@ func (s *stateLendingBook) getAllTradeIds(db Database) []common.Hash {
return tradeIds
}
for id, value := range s.cachedStorage {
if !common.EmptyHash(value) {
if !value.IsZero() {
tradeIds = append(tradeIds, id)
}
}

View file

@ -85,16 +85,16 @@ func (te *tradingExchanges) empty() bool {
if te.data.TotalQuantity != nil && te.data.TotalQuantity.Sign() > 0 {
return false
}
if !common.EmptyHash(te.data.AskRoot) {
if !te.data.AskRoot.IsZero() {
return false
}
if !common.EmptyHash(te.data.BidRoot) {
if !te.data.BidRoot.IsZero() {
return false
}
if !common.EmptyHash(te.data.OrderRoot) {
if !te.data.OrderRoot.IsZero() {
return false
}
if !common.EmptyHash(te.data.LiquidationPriceRoot) {
if !te.data.LiquidationPriceRoot.IsZero() {
return false
}
return true

View file

@ -358,7 +358,7 @@ func (t *TradingStateDB) GetBestAskPrice(orderBook common.Hash) (*big.Int, *big.
stateObject := t.getStateExchangeObject(orderBook)
if stateObject != nil {
priceHash := stateObject.getBestPriceAsksTrie(t.db)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
return Zero, Zero
}
orderList := stateObject.getStateOrderListAskObject(t.db, priceHash)
@ -375,7 +375,7 @@ func (t *TradingStateDB) GetBestBidPrice(orderBook common.Hash) (*big.Int, *big.
stateObject := t.getStateExchangeObject(orderBook)
if stateObject != nil {
priceHash := stateObject.getBestBidsTrie(t.db)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
return Zero, Zero
}
orderList := stateObject.getStateBidOrderListObject(t.db, priceHash)

View file

@ -48,7 +48,7 @@ func (ls *LendingStateDB) DumpInvestingTrie(orderBook common.Hash) (map[*big.Int
it := trie.NewIterator(exhangeObject.getInvestingTrie(ls.db).NodeIterator(nil))
for it.Next() {
interestHash := common.BytesToHash(it.Key)
if common.EmptyHash(interestHash) {
if interestHash.IsZero() {
continue
}
interest := new(big.Int).SetBytes(interestHash.Bytes())
@ -91,7 +91,7 @@ func (ls *LendingStateDB) DumpBorrowingTrie(orderBook common.Hash) (map[*big.Int
it := trie.NewIterator(exhangeObject.getBorrowingTrie(ls.db).NodeIterator(nil))
for it.Next() {
interestHash := common.BytesToHash(it.Key)
if common.EmptyHash(interestHash) {
if interestHash.IsZero() {
continue
}
interest := new(big.Int).SetBytes(interestHash.Bytes())
@ -134,7 +134,7 @@ func (ls *LendingStateDB) GetInvestings(orderBook common.Hash) (map[*big.Int]*bi
it := trie.NewIterator(exhangeObject.getInvestingTrie(ls.db).NodeIterator(nil))
for it.Next() {
interestHash := common.BytesToHash(it.Key)
if common.EmptyHash(interestHash) {
if interestHash.IsZero() {
continue
}
interest := new(big.Int).SetBytes(interestHash.Bytes())
@ -177,7 +177,7 @@ func (ls *LendingStateDB) GetBorrowings(orderBook common.Hash) (map[*big.Int]*bi
it := trie.NewIterator(exhangeObject.getBorrowingTrie(ls.db).NodeIterator(nil))
for it.Next() {
interestHash := common.BytesToHash(it.Key)
if common.EmptyHash(interestHash) {
if interestHash.IsZero() {
continue
}
interest := new(big.Int).SetBytes(interestHash.Bytes())
@ -216,7 +216,7 @@ func (il *itemListState) DumpItemList(db Database) DumpOrderList {
orderListIt := trie.NewIterator(il.getTrie(db).NodeIterator(nil))
for orderListIt.Next() {
keyHash := common.BytesToHash(orderListIt.Key)
if common.EmptyHash(keyHash) {
if keyHash.IsZero() {
continue
}
if _, exist := il.cachedStorage[keyHash]; exist {
@ -227,7 +227,7 @@ func (il *itemListState) DumpItemList(db Database) DumpOrderList {
}
}
for key, value := range il.cachedStorage {
if !common.EmptyHash(value) {
if !value.IsZero() {
mapResult.Orders[new(big.Int).SetBytes(key.Bytes())] = new(big.Int).SetBytes(value.Bytes())
}
}
@ -265,7 +265,7 @@ func (lts *liquidationTimeState) DumpItemList(db Database) DumpOrderList {
orderListIt := trie.NewIterator(lts.getTrie(db).NodeIterator(nil))
for orderListIt.Next() {
keyHash := common.BytesToHash(orderListIt.Key)
if common.EmptyHash(keyHash) {
if keyHash.IsZero() {
continue
}
if _, exist := lts.cachedStorage[keyHash]; exist {
@ -276,7 +276,7 @@ func (lts *liquidationTimeState) DumpItemList(db Database) DumpOrderList {
}
}
for key, value := range lts.cachedStorage {
if !common.EmptyHash(value) {
if !value.IsZero() {
mapResult.Orders[new(big.Int).SetBytes(key.Bytes())] = new(big.Int).SetBytes(value.Bytes())
}
}
@ -303,7 +303,7 @@ func (ls *LendingStateDB) DumpLiquidationTimeTrie(orderBook common.Hash) (map[*b
it := trie.NewIterator(exhangeObject.getLiquidationTimeTrie(ls.db).NodeIterator(nil))
for it.Next() {
unixTimeHash := common.BytesToHash(it.Key)
if common.EmptyHash(unixTimeHash) {
if unixTimeHash.IsZero() {
continue
}
unixTime := new(big.Int).SetBytes(unixTimeHash.Bytes())
@ -346,7 +346,7 @@ func (ls *LendingStateDB) DumpLendingOrderTrie(orderBook common.Hash) (map[*big.
it := trie.NewIterator(exhangeObject.getLendingItemTrie(ls.db).NodeIterator(nil))
for it.Next() {
orderIdHash := common.BytesToHash(it.Key)
if common.EmptyHash(orderIdHash) {
if orderIdHash.IsZero() {
continue
}
orderId := new(big.Int).SetBytes(orderIdHash.Bytes())
@ -386,7 +386,7 @@ func (ls *LendingStateDB) DumpLendingTradeTrie(orderBook common.Hash) (map[*big.
it := trie.NewIterator(exhangeObject.getLendingTradeTrie(ls.db).NodeIterator(nil))
for it.Next() {
tradeIdHash := common.BytesToHash(it.Key)
if common.EmptyHash(tradeIdHash) {
if tradeIdHash.IsZero() {
continue
}
tradeId := new(big.Int).SetBytes(tradeIdHash.Bytes())

View file

@ -70,19 +70,19 @@ func (s *lendingExchangeState) empty() bool {
if s.data.TradeNonce != 0 {
return false
}
if !common.EmptyHash(s.data.InvestingRoot) {
if !s.data.InvestingRoot.IsZero() {
return false
}
if !common.EmptyHash(s.data.BorrowingRoot) {
if !s.data.BorrowingRoot.IsZero() {
return false
}
if !common.EmptyHash(s.data.LendingItemRoot) {
if !s.data.LendingItemRoot.IsZero() {
return false
}
if !common.EmptyHash(s.data.LendingTradeRoot) {
if !s.data.LendingTradeRoot.IsZero() {
return false
}
if !common.EmptyHash(s.data.LiquidationTimeRoot) {
if !s.data.LiquidationTimeRoot.IsZero() {
return false
}
return true

View file

@ -116,7 +116,7 @@ func (lt *liquidationTimeState) getAllTradeIds(db Database) []common.Hash {
return tradeIds
}
for id, value := range lt.cachedStorage {
if !common.EmptyHash(value) {
if !value.IsZero() {
tradeIds = append(tradeIds, id)
}
}

View file

@ -343,7 +343,7 @@ func (ls *LendingStateDB) GetBestInvestingRate(orderBook common.Hash) (*big.Int,
stateObject := ls.getLendingExchange(orderBook)
if stateObject != nil {
investingHash := stateObject.getBestInvestingInterest(ls.db)
if common.EmptyHash(investingHash) {
if investingHash.IsZero() {
return Zero, Zero
}
orderList := stateObject.getInvestingOrderList(ls.db, investingHash)
@ -360,7 +360,7 @@ func (ls *LendingStateDB) GetBestBorrowRate(orderBook common.Hash) (*big.Int, *b
stateObject := ls.getLendingExchange(orderBook)
if stateObject != nil {
priceHash := stateObject.getBestBorrowingInterest(ls.db)
if common.EmptyHash(priceHash) {
if priceHash.IsZero() {
return Zero, Zero
}
orderList := stateObject.getBorrowingOrderList(ls.db, priceHash)

View file

@ -581,7 +581,7 @@ func DoSettleBalance(coinbase common.Address, takerOrder, makerOrder *lendingsta
// masternodes only charge borrower relayer fee
matchingFee = new(big.Int).Add(matchingFee, common.RelayerLendingFee)
if common.EmptyHash(takerExOwner.Hash()) || common.EmptyHash(makerExOwner.Hash()) {
if takerExOwner.Hash().IsZero() || makerExOwner.Hash().IsZero() {
return fmt.Errorf("empty echange owner: taker: %v , maker : %v", takerExOwner, makerExOwner)
}
mapBalances := map[common.Address]map[common.Address]*big.Int{}

View file

@ -19,15 +19,20 @@ package common
import "encoding/hex"
// ToHex returns the hex representation of b, prefixed with '0x'.
// For empty slices, the return value is "0x0".
//
// Deprecated: use hexutil.Encode instead.
func ToHex(b []byte) string {
hex := Bytes2Hex(b)
// Prefer output of "0x0" instead of "0x"
if len(hex) == 0 {
hex = "0"
}
return "0x" + hex
}
// FromHex returns the bytes represented by the hexadecimal string s.
// s may be prefixed with "0x".
func FromHex(s string) []byte {
if len(s) > 1 {
if s[0:2] == "0x" || s[0:2] == "0X" {
@ -43,9 +48,7 @@ func FromHex(s string) []byte {
return Hex2Bytes(s)
}
// Copy bytes
//
// Returns an exact copy of the provided bytes
// CopyBytes returns an exact copy of the provided bytes.
func CopyBytes(b []byte) (copiedBytes []byte) {
if b == nil {
return nil
@ -55,17 +58,23 @@ func CopyBytes(b []byte) (copiedBytes []byte) {
return
}
// hasXDCPrefix validates str begins with 'xdc' or 'XDC'.
func hasXDCPrefix(str string) bool {
return len(str) >= 3 && (str[0] == 'x' || str[0] == 'X') && (str[1] == 'd' || str[1] == 'D') && (str[2] == 'c' || str[2] == 'C')
}
// hasHexPrefix validates str begins with '0x' or '0X'.
func hasHexPrefix(str string) bool {
return len(str) >= 2 && str[0] == '0' && (str[1] == 'x' || str[1] == 'X')
}
// isHexCharacter returns bool of c being a valid hexadecimal.
func isHexCharacter(c byte) bool {
return ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
}
// isHex validates whether each byte is valid hexadecimal string.
func isHex(str string) bool {
if len(str)%2 != 0 {
return false
@ -78,16 +87,18 @@ func isHex(str string) bool {
return true
}
// Bytes2Hex returns the hexadecimal encoding of d.
func Bytes2Hex(d []byte) string {
return hex.EncodeToString(d)
}
// Hex2Bytes returns the bytes represented by the hexadecimal string str.
func Hex2Bytes(str string) []byte {
h, _ := hex.DecodeString(str)
return h
}
// Hex2BytesFixed returns bytes of a specified fixed length flen.
func Hex2BytesFixed(str string, flen int) []byte {
h, _ := hex.DecodeString(str)
if len(h) == flen {
@ -103,6 +114,7 @@ func Hex2BytesFixed(str string, flen int) []byte {
}
}
// RightPadBytes zero-pads slice to the right up to length l.
func RightPadBytes(slice []byte, l int) []byte {
if l <= len(slice) {
return slice
@ -114,6 +126,7 @@ func RightPadBytes(slice []byte, l int) []byte {
return padded
}
// LeftPadBytes zero-pads slice to the left up to length l.
func LeftPadBytes(slice []byte, l int) []byte {
if l <= len(slice) {
return slice

View file

@ -78,7 +78,7 @@ func ParseBig256(s string) (*big.Int, bool) {
return bigint, ok
}
// MustParseBig parses s as a 256 bit big integer and panics if the string is invalid.
// MustParseBig256 parses s as a 256 bit big integer and panics if the string is invalid.
func MustParseBig256(s string) *big.Int {
v, ok := ParseBig256(s)
if !ok {
@ -179,16 +179,15 @@ func U256(x *big.Int) *big.Int {
// S256 interprets x as a two's complement number.
// x must not exceed 256 bits (the result is undefined if it does) and is not modified.
//
// S256(0) = 0
// S256(1) = 1
// S256(2**255) = -2**255
// S256(2**256-1) = -1
// S256(0) = 0
// S256(1) = 1
// S256(2**255) = -2**255
// S256(2**256-1) = -1
func S256(x *big.Int) *big.Int {
if x.Cmp(tt255) < 0 {
return x
} else {
return new(big.Int).Sub(x, tt256)
}
return new(big.Int).Sub(x, tt256)
}
// Exp implements exponentiation by squaring.

View file

@ -34,13 +34,12 @@ func limitUnsigned256(x *Number) *Number {
func limitSigned256(x *Number) *Number {
if x.num.Cmp(tt255) < 0 {
return x
} else {
x.num.Sub(x.num, tt256)
return x
}
x.num.Sub(x.num, tt256)
return x
}
// Number function
// Initialiser is a Number function
type Initialiser func(n int64) *Number
// A Number represents a generic integer with a bounding function limiter. Limit is called after each operations
@ -58,58 +57,58 @@ func NewInitialiser(limiter func(*Number) *Number) Initialiser {
}
}
// Return a Number with a UNSIGNED limiter up to 256 bits
// Uint256 returns a Number with a UNSIGNED limiter up to 256 bits
func Uint256(n int64) *Number {
return &Number{big.NewInt(n), limitUnsigned256}
}
// Return a Number with a SIGNED limiter up to 256 bits
// Int256 returns Number with a SIGNED limiter up to 256 bits
func Int256(n int64) *Number {
return &Number{big.NewInt(n), limitSigned256}
}
// Returns a Number with a SIGNED unlimited size
// Big returns a Number with a SIGNED unlimited size
func Big(n int64) *Number {
return &Number{big.NewInt(n), func(x *Number) *Number { return x }}
}
// Sets i to sum of x+y
// Add sets i to sum of x+y
func (i *Number) Add(x, y *Number) *Number {
i.num.Add(x.num, y.num)
return i.limit(i)
}
// Sets i to difference of x-y
// Sub sets i to difference of x-y
func (i *Number) Sub(x, y *Number) *Number {
i.num.Sub(x.num, y.num)
return i.limit(i)
}
// Sets i to product of x*y
// Mul sets i to product of x*y
func (i *Number) Mul(x, y *Number) *Number {
i.num.Mul(x.num, y.num)
return i.limit(i)
}
// Sets i to the quotient prodject of x/y
// Div sets i to the quotient prodject of x/y
func (i *Number) Div(x, y *Number) *Number {
i.num.Div(x.num, y.num)
return i.limit(i)
}
// Sets i to x % y
// Mod sets i to x % y
func (i *Number) Mod(x, y *Number) *Number {
i.num.Mod(x.num, y.num)
return i.limit(i)
}
// Sets i to x << s
// Lsh sets i to x << s
func (i *Number) Lsh(x *Number, s uint) *Number {
i.num.Lsh(x.num, s)
return i.limit(i)
}
// Sets i to x^y
// Pow sets i to x^y
func (i *Number) Pow(x, y *Number) *Number {
i.num.Exp(x.num, y.num, big.NewInt(0))
return i.limit(i)
@ -117,13 +116,13 @@ func (i *Number) Pow(x, y *Number) *Number {
// Setters
// Set x to i
// Set sets x to i
func (i *Number) Set(x *Number) *Number {
i.num.Set(x.num)
return i.limit(i)
}
// Set x bytes to i
// SetBytes sets x bytes to i
func (i *Number) SetBytes(x []byte) *Number {
i.num.SetBytes(x)
return i.limit(i)
@ -131,21 +130,21 @@ func (i *Number) SetBytes(x []byte) *Number {
// Cmp compares x and y and returns:
//
// -1 if x < y
// 0 if x == y
// +1 if x > y
// -1 if x < y
// 0 if x == y
// +1 if x > y
func (i *Number) Cmp(x *Number) int {
return i.num.Cmp(x.num)
}
// Getters
// Returns the string representation of i
// String returns the string representation of i
func (i *Number) String() string {
return i.num.String()
}
// Returns the byte representation of i
// Bytes returns the byte representation of i
func (i *Number) Bytes() []byte {
return i.num.Bytes()
}
@ -160,17 +159,17 @@ func (i *Number) Int64() int64 {
return i.num.Int64()
}
// Returns the signed version of i
// Int256 returns the signed version of i
func (i *Number) Int256() *Number {
return Int(0).Set(i)
}
// Returns the unsigned version of i
// Uint256 returns the unsigned version of i
func (i *Number) Uint256() *Number {
return Uint(0).Set(i)
}
// Returns the index of the first bit that's set to 1
// FirstBitSet returns the index of the first bit that's set to 1
func (i *Number) FirstBitSet() int {
for j := 0; j < i.num.BitLen(); j++ {
if i.num.Bit(j) > 0 {

View file

@ -30,6 +30,7 @@ func MakeName(name, version string) string {
return fmt.Sprintf("%s/v%s/%s/%s", name, version, runtime.GOOS, runtime.Version())
}
// FileExist checks if a file exists at filePath.
func FileExist(filePath string) bool {
_, err := os.Stat(filePath)
if err != nil && os.IsNotExist(err) {
@ -39,9 +40,10 @@ func FileExist(filePath string) bool {
return true
}
func AbsolutePath(Datadir string, filename string) string {
// AbsolutePath returns datadir + filename, or filename if it is absolute.
func AbsolutePath(datadir string, filename string) string {
if filepath.IsAbs(filename) {
return filename
}
return filepath.Join(Datadir, filename)
return filepath.Join(datadir, filename)
}

View file

@ -106,7 +106,7 @@ func (h Hash) Cmp(other Hash) int {
// IsZero returns if a Hash is empty
func (h Hash) IsZero() bool { return h == Hash{} }
// Get the string representation of the underlying hash
// Str get the string representation of the underlying hash
func (h Hash) Str() string { return string(h[:]) }
// Bytes gets the byte representation of the underlying hash.
@ -161,14 +161,6 @@ func (h *Hash) SetBytes(b []byte) {
copy(h[HashLength-len(b):], b)
}
// Set string `s` to h. If s is larger than len(h) s will be cropped (from left) to fit.
func (h *Hash) SetString(s string) { h.SetBytes([]byte(s)) }
// Sets h to other
func (h *Hash) Set(other Hash) {
copy(h[:], other[:])
}
// Generate implements testing/quick.Generator.
func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
m := rand.Intn(len(h))
@ -178,10 +170,6 @@ func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
return reflect.ValueOf(h)
}
func EmptyHash(h Hash) bool {
return h == Hash{}
}
// UnprefixedHash allows marshaling a Hash without 0x prefix.
type UnprefixedHash Hash
@ -200,6 +188,8 @@ func (h UnprefixedHash) MarshalText() ([]byte, error) {
// Address represents the 20 byte address of an Ethereum account.
type Address [AddressLength]byte
// BytesToAddress returns Address with value b.
// If b is larger than len(h), b will be cropped from the left.
func BytesToAddress(b []byte) Address {
var a Address
a.SetBytes(b)
@ -231,11 +221,17 @@ func IsHexAddress(s string) bool {
// IsZero returns if a address is empty
func (a Address) IsZero() bool { return a == Address{} }
// Get the string representation of the underlying address
func (a Address) Str() string { return string(a[:]) }
// Str gets the string representation of the underlying address
func (a Address) Str() string { return string(a[:]) }
// Bytes gets the string representation of the underlying address.
func (a Address) Bytes() []byte { return a[:] }
// Big converts an address to a big integer.
func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }
func (a Address) Hash() Hash { return BytesToHash(a[:]) }
// Hash converts an address to a hash by left-padding it with zeros.
func (a Address) Hash() Hash { return BytesToHash(a[:]) }
// Hex returns an EIP55-compliant hex string representation of the address.
func (a Address) Hex() string {
@ -259,7 +255,7 @@ func (a Address) Hex() string {
return "xdc" + string(result)
}
// String implements the stringer interface and is used also by the logger.
// String implements fmt.Stringer.
func (a Address) String() string {
return a.Hex()
}
@ -270,7 +266,8 @@ func (a Address) Format(s fmt.State, c rune) {
fmt.Fprintf(s, "%"+string(c), a[:])
}
// Sets the address to the value of b. If b is larger than len(a) it will panic
// SetBytes sets the address to the value of b.
// If b is larger than len(a) it will panic.
func (a *Address) SetBytes(b []byte) {
if len(b) > len(a) {
b = b[len(b)-AddressLength:]
@ -278,14 +275,6 @@ func (a *Address) SetBytes(b []byte) {
copy(a[AddressLength-len(b):], b)
}
// Set string `s` to a. If s is larger than len(a) it will panic
func (a *Address) SetString(s string) { a.SetBytes([]byte(s)) }
// Sets a to other
func (a *Address) Set(other Address) {
copy(a[:], other[:])
}
// MarshalText returns the hex representation of a.
func (a Address) MarshalText() ([]byte, error) {
// Handle '0x' or 'xdc' prefix here.
@ -306,7 +295,7 @@ func (a *Address) UnmarshalJSON(input []byte) error {
return hexutil.UnmarshalFixedJSON(addressT, input, a[:])
}
// UnprefixedHash allows marshaling an Address without 0x prefix.
// UnprefixedAddress allows marshaling an Address without 0x prefix.
type UnprefixedAddress Address
// UnmarshalText decodes the address from hex. The 0x prefix is optional.
@ -319,7 +308,7 @@ func (a UnprefixedAddress) MarshalText() ([]byte, error) {
return []byte(hex.EncodeToString(a[:])), nil
}
// Extract validators from byte array.
// RemoveItemFromArray extracts validators from byte array.
func RemoveItemFromArray(array []Address, items []Address) []Address {
// Create newArray to stop append change array value
newArray := make([]Address, len(array))
@ -340,7 +329,7 @@ func RemoveItemFromArray(array []Address, items []Address) []Address {
return newArray
}
// Extract validators from byte array.
// ExtractAddressToBytes extracts validators from byte array.
func ExtractAddressToBytes(penalties []Address) []byte {
data := []byte{}
for _, signer := range penalties {

View file

@ -1,64 +0,0 @@
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// +build none
//sed -e 's/_N_/Hash/g' -e 's/_S_/32/g' -e '1d' types_template.go | gofmt -w hash.go
package common
import "math/big"
type _N_ [_S_]byte
func BytesTo_N_(b []byte) _N_ {
var h _N_
h.SetBytes(b)
return h
}
func StringTo_N_(s string) _N_ { return BytesTo_N_([]byte(s)) }
func BigTo_N_(b *big.Int) _N_ { return BytesTo_N_(b.Bytes()) }
func HexTo_N_(s string) _N_ { return BytesTo_N_(FromHex(s)) }
// Don't use the default 'String' method in case we want to overwrite
// Get the string representation of the underlying hash
func (h _N_) Str() string { return string(h[:]) }
func (h _N_) Bytes() []byte { return h[:] }
func (h _N_) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
func (h _N_) Hex() string { return "0x" + Bytes2Hex(h[:]) }
// Sets the hash to the value of b. If b is larger than len(h) it will panic
func (h *_N_) SetBytes(b []byte) {
// Use the right most bytes
if len(b) > len(h) {
b = b[len(b)-_S_:]
}
// Reverse the loop
for i := len(b) - 1; i >= 0; i-- {
h[_S_-len(b)+i] = b[i]
}
}
// Set string `s` to h. If s is larger than len(h) it will panic
func (h *_N_) SetString(s string) { h.SetBytes([]byte(s)) }
// Sets h to other
func (h *_N_) Set(other _N_) {
for i, v := range other {
h[i] = v
}
}

View file

@ -957,7 +957,7 @@ func (bc *BlockChain) saveData() {
author, _ := bc.Engine().Author(recent.Header())
if tradingService != nil {
tradingRoot, _ := tradingService.GetTradingStateRoot(recent, author)
if !common.EmptyHash(tradingRoot) && tradingTriedb != nil {
if !tradingRoot.IsZero() && tradingTriedb != nil {
if err := tradingTriedb.Commit(tradingRoot, true); err != nil {
log.Error("Failed to commit trading state recent state trie", "err", err)
}
@ -965,7 +965,7 @@ func (bc *BlockChain) saveData() {
}
if lendingService != nil {
lendingRoot, _ := lendingService.GetLendingStateRoot(recent, author)
if !common.EmptyHash(lendingRoot) && lendingTriedb != nil {
if !lendingRoot.IsZero() && lendingTriedb != nil {
if err := lendingTriedb.Commit(lendingRoot, true); err != nil {
log.Error("Failed to commit lending state recent state trie", "err", err)
}

View file

@ -100,7 +100,7 @@ func (s *StateSuite) TestNull(c *checker.C) {
s.state.SetState(address, common.Hash{}, value)
s.state.Commit(false)
value = s.state.GetState(address, common.Hash{})
if !common.EmptyHash(value) {
if !value.IsZero() {
c.Errorf("expected empty hash. got %x", value)
}
}

View file

@ -51,7 +51,7 @@ func GetTRC21FeeCapacityFromState(statedb *StateDB) map[common.Address]*big.Int
for i := uint64(0); i < tokenCount; i++ {
key := GetLocDynamicArrAtElement(slotTokensHash, i, 1)
value := statedb.GetState(common.TRC21IssuerSMC, key)
if !common.EmptyHash(value) {
if !value.IsZero() {
token := common.BytesToAddress(value.Bytes())
balanceKey := GetLocMappingAtKey(token.Hash(), slotTokensState)
balanceHash := statedb.GetState(common.TRC21IssuerSMC, common.BigToHash(balanceKey))
@ -68,14 +68,14 @@ func PayFeeWithTRC21TxFail(statedb *StateDB, from common.Address, token common.A
slotBalanceTrc21 := SlotTRC21Token["balances"]
balanceKey := GetLocMappingAtKey(from.Hash(), slotBalanceTrc21)
balanceHash := statedb.GetState(token, common.BigToHash(balanceKey))
if !common.EmptyHash(balanceHash) {
if !balanceHash.IsZero() {
balance := balanceHash.Big()
feeUsed := big.NewInt(0)
if balance.Cmp(feeUsed) <= 0 {
return
}
issuerTokenKey := GetLocSimpleVariable(SlotTRC21Token["issuer"])
if common.EmptyHash(issuerTokenKey) {
if issuerTokenKey.IsZero() {
return
}
issuerAddr := common.BytesToAddress(statedb.GetState(token, issuerTokenKey).Bytes())
@ -106,7 +106,7 @@ func ValidateTRC21Tx(statedb *StateDB, from common.Address, token common.Address
balanceKey := GetLocMappingAtKey(from.Hash(), slotBalanceTrc21)
balanceHash := statedb.GetState(token, common.BigToHash(balanceKey))
if !common.EmptyHash(balanceHash) {
if !balanceHash.IsZero() {
balance := balanceHash.Big()
minFeeTokenKey := GetLocSimpleVariable(SlotTRC21Token["minFee"])
minFeeHash := statedb.GetState(token, minFeeTokenKey)
@ -129,7 +129,7 @@ func ValidateTRC21Tx(statedb *StateDB, from common.Address, token common.Address
} else {
// we both accept tx with balance = 0 and fee = 0
minFeeTokenKey := GetLocSimpleVariable(SlotTRC21Token["minFee"])
if !common.EmptyHash(minFeeTokenKey) {
if !minFeeTokenKey.IsZero() {
return true
}
}

View file

@ -492,7 +492,7 @@ func (pool *OrderPool) validateOrder(tx *types.OrderTransaction) error {
var signer = types.OrderTxSigner{}
if !tx.IsCancelledOrder() {
if !common.EmptyHash(tx.OrderHash()) {
if !tx.OrderHash().IsZero() {
if signer.Hash(tx) != tx.OrderHash() {
return ErrInvalidOrderHash
}

View file

@ -682,7 +682,7 @@ func (d *Downloader) findAncestor(p *peerConnection, height uint64) (uint64, err
}
}
// If the head fetch already found an ancestor, return
if !common.EmptyHash(hash) {
if !hash.IsZero() {
if int64(number) <= floor {
p.log.Warn("Ancestor below allowance", "number", number, "hash", hash, "allowance", floor)
return 0, errInvalidAncestor