types.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package common
  17. import (
  18. "bytes"
  19. "database/sql/driver"
  20. "encoding/hex"
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "math/big"
  25. "math/rand"
  26. "reflect"
  27. "strings"
  28. "github.com/ethereum/go-ethereum/common/hexutil"
  29. "golang.org/x/crypto/sha3"
  30. )
  31. // Lengths of hashes and addresses in bytes.
  32. const (
  33. // HashLength is the expected length of the hash
  34. HashLength = 32
  35. // AddressLength is the expected length of the address
  36. AddressLength = 20
  37. )
  38. var (
  39. hashT = reflect.TypeOf(Hash{})
  40. addressT = reflect.TypeOf(Address{})
  41. )
  42. // Hash represents the 32 byte Keccak256 hash of arbitrary data.
  43. type Hash [HashLength]byte
  44. // BytesToHash sets b to hash.
  45. // If b is larger than len(h), b will be cropped from the left.
  46. func BytesToHash(b []byte) Hash {
  47. var h Hash
  48. h.SetBytes(b)
  49. return h
  50. }
  51. // BigToHash sets byte representation of b to hash.
  52. // If b is larger than len(h), b will be cropped from the left.
  53. func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
  54. // HexToHash sets byte representation of s to hash.
  55. // If b is larger than len(h), b will be cropped from the left.
  56. func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }
  57. // Bytes gets the byte representation of the underlying hash.
  58. func (h Hash) Bytes() []byte { return h[:] }
  59. // Big converts a hash to a big integer.
  60. func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
  61. // Hex converts a hash to a hex string.
  62. func (h Hash) Hex() string { return hexutil.Encode(h[:]) }
  63. // TerminalString implements log.TerminalStringer, formatting a string for console
  64. // output during logging.
  65. func (h Hash) TerminalString() string {
  66. return fmt.Sprintf("%x..%x", h[:3], h[29:])
  67. }
  68. // String implements the stringer interface and is used also by the logger when
  69. // doing full logging into a file.
  70. func (h Hash) String() string {
  71. return h.Hex()
  72. }
  73. // Format implements fmt.Formatter.
  74. // Hash supports the %v, %s, %q, %x, %X and %d format verbs.
  75. func (h Hash) Format(s fmt.State, c rune) {
  76. hexb := make([]byte, 2+len(h)*2)
  77. copy(hexb, "0x")
  78. hex.Encode(hexb[2:], h[:])
  79. switch c {
  80. case 'x', 'X':
  81. if !s.Flag('#') {
  82. hexb = hexb[2:]
  83. }
  84. if c == 'X' {
  85. hexb = bytes.ToUpper(hexb)
  86. }
  87. fallthrough
  88. case 'v', 's':
  89. s.Write(hexb)
  90. case 'q':
  91. q := []byte{'"'}
  92. s.Write(q)
  93. s.Write(hexb)
  94. s.Write(q)
  95. case 'd':
  96. fmt.Fprint(s, ([len(h)]byte)(h))
  97. default:
  98. fmt.Fprintf(s, "%%!%c(hash=%x)", c, h)
  99. }
  100. }
  101. // UnmarshalText parses a hash in hex syntax.
  102. func (h *Hash) UnmarshalText(input []byte) error {
  103. return hexutil.UnmarshalFixedText("Hash", input, h[:])
  104. }
  105. // UnmarshalJSON parses a hash in hex syntax.
  106. func (h *Hash) UnmarshalJSON(input []byte) error {
  107. return hexutil.UnmarshalFixedJSON(hashT, input, h[:])
  108. }
  109. // MarshalText returns the hex representation of h.
  110. func (h Hash) MarshalText() ([]byte, error) {
  111. return hexutil.Bytes(h[:]).MarshalText()
  112. }
  113. // SetBytes sets the hash to the value of b.
  114. // If b is larger than len(h), b will be cropped from the left.
  115. func (h *Hash) SetBytes(b []byte) {
  116. if len(b) > len(h) {
  117. b = b[len(b)-HashLength:]
  118. }
  119. copy(h[HashLength-len(b):], b)
  120. }
  121. // Generate implements testing/quick.Generator.
  122. func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
  123. m := rand.Intn(len(h))
  124. for i := len(h) - 1; i > m; i-- {
  125. h[i] = byte(rand.Uint32())
  126. }
  127. return reflect.ValueOf(h)
  128. }
  129. // Scan implements Scanner for database/sql.
  130. func (h *Hash) Scan(src interface{}) error {
  131. srcB, ok := src.([]byte)
  132. if !ok {
  133. return fmt.Errorf("can't scan %T into Hash", src)
  134. }
  135. if len(srcB) != HashLength {
  136. return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength)
  137. }
  138. copy(h[:], srcB)
  139. return nil
  140. }
  141. // Value implements valuer for database/sql.
  142. func (h Hash) Value() (driver.Value, error) {
  143. return h[:], nil
  144. }
  145. // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.
  146. func (Hash) ImplementsGraphQLType(name string) bool { return name == "Bytes32" }
  147. // UnmarshalGraphQL unmarshals the provided GraphQL query data.
  148. func (h *Hash) UnmarshalGraphQL(input interface{}) error {
  149. var err error
  150. switch input := input.(type) {
  151. case string:
  152. err = h.UnmarshalText([]byte(input))
  153. default:
  154. err = fmt.Errorf("unexpected type %T for Hash", input)
  155. }
  156. return err
  157. }
  158. // UnprefixedHash allows marshaling a Hash without 0x prefix.
  159. type UnprefixedHash Hash
  160. // UnmarshalText decodes the hash from hex. The 0x prefix is optional.
  161. func (h *UnprefixedHash) UnmarshalText(input []byte) error {
  162. return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:])
  163. }
  164. // MarshalText encodes the hash as hex.
  165. func (h UnprefixedHash) MarshalText() ([]byte, error) {
  166. return []byte(hex.EncodeToString(h[:])), nil
  167. }
  168. /////////// Address
  169. // Address represents the 20 byte address of an Ethereum account.
  170. type Address [AddressLength]byte
  171. // BytesToAddress returns Address with value b.
  172. // If b is larger than len(h), b will be cropped from the left.
  173. func BytesToAddress(b []byte) Address {
  174. var a Address
  175. a.SetBytes(b)
  176. return a
  177. }
  178. // BigToAddress returns Address with byte values of b.
  179. // If b is larger than len(h), b will be cropped from the left.
  180. func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }
  181. // HexToAddress returns Address with byte values of s.
  182. // If s is larger than len(h), s will be cropped from the left.
  183. func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) }
  184. // IsHexAddress verifies whether a string can represent a valid hex-encoded
  185. // Ethereum address or not.
  186. func IsHexAddress(s string) bool {
  187. if has0xPrefix(s) {
  188. s = s[2:]
  189. }
  190. return len(s) == 2*AddressLength && isHex(s)
  191. }
  192. // Bytes gets the string representation of the underlying address.
  193. func (a Address) Bytes() []byte { return a[:] }
  194. // Hash converts an address to a hash by left-padding it with zeros.
  195. func (a Address) Hash() Hash { return BytesToHash(a[:]) }
  196. // Hex returns an EIP55-compliant hex string representation of the address.
  197. func (a Address) Hex() string {
  198. return string(a.checksumHex())
  199. }
  200. // String implements fmt.Stringer.
  201. func (a Address) String() string {
  202. return a.Hex()
  203. }
  204. func (a *Address) checksumHex() []byte {
  205. buf := a.hex()
  206. // compute checksum
  207. sha := sha3.NewLegacyKeccak256()
  208. sha.Write(buf[2:])
  209. hash := sha.Sum(nil)
  210. for i := 2; i < len(buf); i++ {
  211. hashByte := hash[(i-2)/2]
  212. if i%2 == 0 {
  213. hashByte = hashByte >> 4
  214. } else {
  215. hashByte &= 0xf
  216. }
  217. if buf[i] > '9' && hashByte > 7 {
  218. buf[i] -= 32
  219. }
  220. }
  221. return buf[:]
  222. }
  223. func (a Address) hex() []byte {
  224. var buf [len(a)*2 + 2]byte
  225. copy(buf[:2], "0x")
  226. hex.Encode(buf[2:], a[:])
  227. return buf[:]
  228. }
  229. // Format implements fmt.Formatter.
  230. // Address supports the %v, %s, %q, %x, %X and %d format verbs.
  231. func (a Address) Format(s fmt.State, c rune) {
  232. switch c {
  233. case 'v', 's':
  234. s.Write(a.checksumHex())
  235. case 'q':
  236. q := []byte{'"'}
  237. s.Write(q)
  238. s.Write(a.checksumHex())
  239. s.Write(q)
  240. case 'x', 'X':
  241. // %x disables the checksum.
  242. hex := a.hex()
  243. if !s.Flag('#') {
  244. hex = hex[2:]
  245. }
  246. if c == 'X' {
  247. hex = bytes.ToUpper(hex)
  248. }
  249. s.Write(hex)
  250. case 'd':
  251. fmt.Fprint(s, ([len(a)]byte)(a))
  252. default:
  253. fmt.Fprintf(s, "%%!%c(address=%x)", c, a)
  254. }
  255. }
  256. // SetBytes sets the address to the value of b.
  257. // If b is larger than len(a), b will be cropped from the left.
  258. func (a *Address) SetBytes(b []byte) {
  259. if len(b) > len(a) {
  260. b = b[len(b)-AddressLength:]
  261. }
  262. copy(a[AddressLength-len(b):], b)
  263. }
  264. // MarshalText returns the hex representation of a.
  265. func (a Address) MarshalText() ([]byte, error) {
  266. return hexutil.Bytes(a[:]).MarshalText()
  267. }
  268. // UnmarshalText parses a hash in hex syntax.
  269. func (a *Address) UnmarshalText(input []byte) error {
  270. return hexutil.UnmarshalFixedText("Address", input, a[:])
  271. }
  272. // UnmarshalJSON parses a hash in hex syntax.
  273. func (a *Address) UnmarshalJSON(input []byte) error {
  274. return hexutil.UnmarshalFixedJSON(addressT, input, a[:])
  275. }
  276. // Scan implements Scanner for database/sql.
  277. func (a *Address) Scan(src interface{}) error {
  278. srcB, ok := src.([]byte)
  279. if !ok {
  280. return fmt.Errorf("can't scan %T into Address", src)
  281. }
  282. if len(srcB) != AddressLength {
  283. return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength)
  284. }
  285. copy(a[:], srcB)
  286. return nil
  287. }
  288. // Value implements valuer for database/sql.
  289. func (a Address) Value() (driver.Value, error) {
  290. return a[:], nil
  291. }
  292. // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.
  293. func (a Address) ImplementsGraphQLType(name string) bool { return name == "Address" }
  294. // UnmarshalGraphQL unmarshals the provided GraphQL query data.
  295. func (a *Address) UnmarshalGraphQL(input interface{}) error {
  296. var err error
  297. switch input := input.(type) {
  298. case string:
  299. err = a.UnmarshalText([]byte(input))
  300. default:
  301. err = fmt.Errorf("unexpected type %T for Address", input)
  302. }
  303. return err
  304. }
  305. // UnprefixedAddress allows marshaling an Address without 0x prefix.
  306. type UnprefixedAddress Address
  307. // UnmarshalText decodes the address from hex. The 0x prefix is optional.
  308. func (a *UnprefixedAddress) UnmarshalText(input []byte) error {
  309. return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:])
  310. }
  311. // MarshalText encodes the address as hex.
  312. func (a UnprefixedAddress) MarshalText() ([]byte, error) {
  313. return []byte(hex.EncodeToString(a[:])), nil
  314. }
  315. // MixedcaseAddress retains the original string, which may or may not be
  316. // correctly checksummed
  317. type MixedcaseAddress struct {
  318. addr Address
  319. original string
  320. }
  321. // NewMixedcaseAddress constructor (mainly for testing)
  322. func NewMixedcaseAddress(addr Address) MixedcaseAddress {
  323. return MixedcaseAddress{addr: addr, original: addr.Hex()}
  324. }
  325. // NewMixedcaseAddressFromString is mainly meant for unit-testing
  326. func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error) {
  327. if !IsHexAddress(hexaddr) {
  328. return nil, errors.New("invalid address")
  329. }
  330. a := FromHex(hexaddr)
  331. return &MixedcaseAddress{addr: BytesToAddress(a), original: hexaddr}, nil
  332. }
  333. // UnmarshalJSON parses MixedcaseAddress
  334. func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error {
  335. if err := hexutil.UnmarshalFixedJSON(addressT, input, ma.addr[:]); err != nil {
  336. return err
  337. }
  338. return json.Unmarshal(input, &ma.original)
  339. }
  340. // MarshalJSON marshals the original value
  341. func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error) {
  342. if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") {
  343. return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:]))
  344. }
  345. return json.Marshal(fmt.Sprintf("0x%s", ma.original))
  346. }
  347. // Address returns the address
  348. func (ma *MixedcaseAddress) Address() Address {
  349. return ma.addr
  350. }
  351. // String implements fmt.Stringer
  352. func (ma *MixedcaseAddress) String() string {
  353. if ma.ValidChecksum() {
  354. return fmt.Sprintf("%s [chksum ok]", ma.original)
  355. }
  356. return fmt.Sprintf("%s [chksum INVALID]", ma.original)
  357. }
  358. // ValidChecksum returns true if the address has valid checksum
  359. func (ma *MixedcaseAddress) ValidChecksum() bool {
  360. return ma.original == ma.addr.Hex()
  361. }
  362. // Original returns the mixed-case input string
  363. func (ma *MixedcaseAddress) Original() string {
  364. return ma.original
  365. }