types.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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/base64"
  21. "encoding/hex"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "math/big"
  27. "math/rand"
  28. "reflect"
  29. "strings"
  30. "github.com/ethereum/go-ethereum/common/hexutil"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. "golang.org/x/crypto/sha3"
  33. )
  34. // Lengths of hashes and addresses in bytes.
  35. const (
  36. // HashLength is the expected length of the hash
  37. HashLength = 32
  38. // AddressLength is the expected length of the address
  39. AddressLength = 20
  40. // length of the hash returned by Private Transaction Manager
  41. EncryptedPayloadHashLength = 64
  42. )
  43. var (
  44. ErrNotPrivateContract = errors.New("the provided address is not a private contract")
  45. ErrNoAccountExtraData = errors.New("no account extra data found")
  46. hashT = reflect.TypeOf(Hash{})
  47. addressT = reflect.TypeOf(Address{})
  48. )
  49. // Hash, returned by Private Transaction Manager, represents the 64-byte hash of encrypted payload
  50. type EncryptedPayloadHash [EncryptedPayloadHashLength]byte
  51. // Using map to enable fast lookup
  52. type EncryptedPayloadHashes map[EncryptedPayloadHash]struct{}
  53. func (h *EncryptedPayloadHash) MarshalJSON() (j []byte, err error) {
  54. return json.Marshal(h.ToBase64())
  55. }
  56. func (h *EncryptedPayloadHash) UnmarshalJSON(j []byte) (err error) {
  57. var ephStr string
  58. err = json.Unmarshal(j, &ephStr)
  59. if err != nil {
  60. return err
  61. }
  62. eph, err := Base64ToEncryptedPayloadHash(ephStr)
  63. if err != nil {
  64. return err
  65. }
  66. h.SetBytes(eph.Bytes())
  67. return nil
  68. }
  69. func (h *EncryptedPayloadHashes) MarshalJSON() (j []byte, err error) {
  70. return json.Marshal(h.ToBase64s())
  71. }
  72. func (h *EncryptedPayloadHashes) UnmarshalJSON(j []byte) (err error) {
  73. var ephStrArray []string
  74. err = json.Unmarshal(j, &ephStrArray)
  75. if err != nil {
  76. return err
  77. }
  78. for _, str := range ephStrArray {
  79. eph, err := Base64ToEncryptedPayloadHash(str)
  80. if err != nil {
  81. return err
  82. }
  83. h.Add(eph)
  84. }
  85. return nil
  86. }
  87. // BytesToEncryptedPayloadHash sets b to EncryptedPayloadHash.
  88. // If b is larger than len(h), b will be cropped from the left.
  89. func BytesToEncryptedPayloadHash(b []byte) EncryptedPayloadHash {
  90. var h EncryptedPayloadHash
  91. h.SetBytes(b)
  92. return h
  93. }
  94. func Base64ToEncryptedPayloadHash(b64 string) (EncryptedPayloadHash, error) {
  95. bytes, err := base64.StdEncoding.DecodeString(b64)
  96. if err != nil {
  97. return EncryptedPayloadHash{}, fmt.Errorf("unable to convert base64 string %s to EncryptedPayloadHash. Cause: %v", b64, err)
  98. }
  99. return BytesToEncryptedPayloadHash(bytes), nil
  100. }
  101. func (eph *EncryptedPayloadHash) SetBytes(b []byte) {
  102. if len(b) > len(eph) {
  103. b = b[len(b)-EncryptedPayloadHashLength:]
  104. }
  105. copy(eph[EncryptedPayloadHashLength-len(b):], b)
  106. }
  107. func (eph EncryptedPayloadHash) Hex() string {
  108. return hexutil.Encode(eph[:])
  109. }
  110. func (eph EncryptedPayloadHash) Bytes() []byte {
  111. return eph[:]
  112. }
  113. func (eph EncryptedPayloadHash) String() string {
  114. return eph.Hex()
  115. }
  116. func (eph EncryptedPayloadHash) ToBase64() string {
  117. return base64.StdEncoding.EncodeToString(eph[:])
  118. }
  119. func (eph EncryptedPayloadHash) TerminalString() string {
  120. return fmt.Sprintf("%x…%x", eph[:3], eph[EncryptedPayloadHashLength-3:])
  121. }
  122. func (eph EncryptedPayloadHash) BytesTypeRef() *hexutil.Bytes {
  123. b := hexutil.Bytes(eph.Bytes())
  124. return &b
  125. }
  126. func EmptyEncryptedPayloadHash(eph EncryptedPayloadHash) bool {
  127. return eph == EncryptedPayloadHash{}
  128. }
  129. // Hash represents the 32 byte Keccak256 hash of arbitrary data.
  130. type Hash [HashLength]byte
  131. // BytesToHash sets b to hash.
  132. // If b is larger than len(h), b will be cropped from the left.
  133. func BytesToHash(b []byte) Hash {
  134. var h Hash
  135. h.SetBytes(b)
  136. return h
  137. }
  138. func StringToHash(s string) Hash { return BytesToHash([]byte(s)) } // dep: Istanbul
  139. // BigToHash sets byte representation of b to hash.
  140. // If b is larger than len(h), b will be cropped from the left.
  141. func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
  142. // HexToHash sets byte representation of s to hash.
  143. // If b is larger than len(h), b will be cropped from the left.
  144. func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }
  145. // Bytes gets the byte representation of the underlying hash.
  146. func (h Hash) Bytes() []byte { return h[:] }
  147. // Big converts a hash to a big integer.
  148. func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
  149. // Hex converts a hash to a hex string.
  150. func (h Hash) Hex() string { return hexutil.Encode(h[:]) }
  151. // TerminalString implements log.TerminalStringer, formatting a string for console
  152. // output during logging.
  153. func (h Hash) TerminalString() string {
  154. return fmt.Sprintf("%x..%x", h[:3], h[29:])
  155. }
  156. // String implements the stringer interface and is used also by the logger when
  157. // doing full logging into a file.
  158. func (h Hash) String() string {
  159. return h.Hex()
  160. }
  161. // Format implements fmt.Formatter.
  162. // Hash supports the %v, %s, %v, %x, %X and %d format verbs.
  163. func (h Hash) Format(s fmt.State, c rune) {
  164. hexb := make([]byte, 2+len(h)*2)
  165. copy(hexb, "0x")
  166. hex.Encode(hexb[2:], h[:])
  167. switch c {
  168. case 'x', 'X':
  169. if !s.Flag('#') {
  170. hexb = hexb[2:]
  171. }
  172. if c == 'X' {
  173. hexb = bytes.ToUpper(hexb)
  174. }
  175. fallthrough
  176. case 'v', 's':
  177. s.Write(hexb)
  178. case 'q':
  179. q := []byte{'"'}
  180. s.Write(q)
  181. s.Write(hexb)
  182. s.Write(q)
  183. case 'd':
  184. fmt.Fprint(s, ([len(h)]byte)(h))
  185. default:
  186. fmt.Fprintf(s, "%%!%c(hash=%x)", c, h)
  187. }
  188. }
  189. // UnmarshalText parses a hash in hex syntax.
  190. func (h *Hash) UnmarshalText(input []byte) error {
  191. return hexutil.UnmarshalFixedText("Hash", input, h[:])
  192. }
  193. // UnmarshalJSON parses a hash in hex syntax.
  194. func (h *Hash) UnmarshalJSON(input []byte) error {
  195. return hexutil.UnmarshalFixedJSON(hashT, input, h[:])
  196. }
  197. // MarshalText returns the hex representation of h.
  198. func (h Hash) MarshalText() ([]byte, error) {
  199. return hexutil.Bytes(h[:]).MarshalText()
  200. }
  201. // SetBytes sets the hash to the value of b.
  202. // If b is larger than len(h), b will be cropped from the left.
  203. func (h *Hash) SetBytes(b []byte) {
  204. if len(b) > len(h) {
  205. b = b[len(b)-HashLength:]
  206. }
  207. copy(h[HashLength-len(b):], b)
  208. }
  209. func EmptyHash(h Hash) bool {
  210. return h == Hash{}
  211. }
  212. // Generate implements testing/quick.Generator.
  213. func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
  214. m := rand.Intn(len(h))
  215. for i := len(h) - 1; i > m; i-- {
  216. h[i] = byte(rand.Uint32())
  217. }
  218. return reflect.ValueOf(h)
  219. }
  220. func (h Hash) ToBase64() string {
  221. return base64.StdEncoding.EncodeToString(h.Bytes())
  222. }
  223. // Decode base64 string to Hash
  224. // if String is empty then return empty hash
  225. func Base64ToHash(b64 string) (Hash, error) {
  226. if b64 == "" {
  227. return Hash{}, nil
  228. }
  229. bytes, err := base64.StdEncoding.DecodeString(b64)
  230. if err != nil {
  231. return Hash{}, fmt.Errorf("unable to convert base64 string %s to Hash. Cause: %v", b64, err)
  232. }
  233. return BytesToHash(bytes), nil
  234. }
  235. // Scan implements Scanner for database/sql.
  236. func (h *Hash) Scan(src interface{}) error {
  237. srcB, ok := src.([]byte)
  238. if !ok {
  239. return fmt.Errorf("can't scan %T into Hash", src)
  240. }
  241. if len(srcB) != HashLength {
  242. return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength)
  243. }
  244. copy(h[:], srcB)
  245. return nil
  246. }
  247. // Value implements valuer for database/sql.
  248. func (h Hash) Value() (driver.Value, error) {
  249. return h[:], nil
  250. }
  251. // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.
  252. func (Hash) ImplementsGraphQLType(name string) bool { return name == "Bytes32" }
  253. // UnmarshalGraphQL unmarshals the provided GraphQL query data.
  254. func (h *Hash) UnmarshalGraphQL(input interface{}) error {
  255. var err error
  256. switch input := input.(type) {
  257. case string:
  258. err = h.UnmarshalText([]byte(input))
  259. default:
  260. err = fmt.Errorf("unexpected type %T for Hash", input)
  261. }
  262. return err
  263. }
  264. // UnprefixedHash allows marshaling a Hash without 0x prefix.
  265. type UnprefixedHash Hash
  266. // UnmarshalText decodes the hash from hex. The 0x prefix is optional.
  267. func (h *UnprefixedHash) UnmarshalText(input []byte) error {
  268. return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:])
  269. }
  270. // MarshalText encodes the hash as hex.
  271. func (h UnprefixedHash) MarshalText() ([]byte, error) {
  272. return []byte(hex.EncodeToString(h[:])), nil
  273. }
  274. func (ephs EncryptedPayloadHashes) ToBase64s() []string {
  275. a := make([]string, 0, len(ephs))
  276. for eph := range ephs {
  277. a = append(a, eph.ToBase64())
  278. }
  279. return a
  280. }
  281. func (ephs EncryptedPayloadHashes) NotExist(eph EncryptedPayloadHash) bool {
  282. _, ok := ephs[eph]
  283. return !ok
  284. }
  285. func (ephs EncryptedPayloadHashes) Add(eph EncryptedPayloadHash) {
  286. ephs[eph] = struct{}{}
  287. }
  288. func (ephs EncryptedPayloadHashes) EncodeRLP(writer io.Writer) error {
  289. encryptedPayloadHashesArray := make([]EncryptedPayloadHash, len(ephs))
  290. idx := 0
  291. for key := range ephs {
  292. encryptedPayloadHashesArray[idx] = key
  293. idx++
  294. }
  295. return rlp.Encode(writer, encryptedPayloadHashesArray)
  296. }
  297. func (ephs EncryptedPayloadHashes) DecodeRLP(stream *rlp.Stream) error {
  298. var encryptedPayloadHashesRLP []EncryptedPayloadHash
  299. if err := stream.Decode(&encryptedPayloadHashesRLP); err != nil {
  300. return err
  301. }
  302. for _, val := range encryptedPayloadHashesRLP {
  303. ephs.Add(val)
  304. }
  305. return nil
  306. }
  307. func Base64sToEncryptedPayloadHashes(b64s []string) (EncryptedPayloadHashes, error) {
  308. ephs := make(EncryptedPayloadHashes)
  309. for _, b64 := range b64s {
  310. data, err := Base64ToEncryptedPayloadHash(b64)
  311. if err != nil {
  312. return nil, err
  313. }
  314. ephs.Add(data)
  315. }
  316. return ephs, nil
  317. }
  318. // Print hex but only first 3 and last 3 bytes
  319. func FormatTerminalString(data []byte) string {
  320. l := len(data)
  321. if l > 0 {
  322. if l > 6 {
  323. return fmt.Sprintf("%x…%x", data[:3], data[l-3:])
  324. } else {
  325. return fmt.Sprintf("%x", data[:])
  326. }
  327. }
  328. return ""
  329. }
  330. /////////// Address
  331. // Address represents the 20 byte address of an Ethereum account.
  332. type Address [AddressLength]byte
  333. // BytesToAddress returns Address with value b.
  334. // If b is larger than len(h), b will be cropped from the left.
  335. func BytesToAddress(b []byte) Address {
  336. var a Address
  337. a.SetBytes(b)
  338. return a
  339. }
  340. func StringToAddress(s string) Address { return BytesToAddress([]byte(s)) } // dep: Istanbul
  341. // BigToAddress returns Address with byte values of b.
  342. // If b is larger than len(h), b will be cropped from the left.
  343. func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }
  344. // HexToAddress returns Address with byte values of s.
  345. // If s is larger than len(h), s will be cropped from the left.
  346. func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) }
  347. // IsHexAddress verifies whether a string can represent a valid hex-encoded
  348. // Ethereum address or not.
  349. func IsHexAddress(s string) bool {
  350. if has0xPrefix(s) {
  351. s = s[2:]
  352. }
  353. return len(s) == 2*AddressLength && isHex(s)
  354. }
  355. // Bytes gets the string representation of the underlying address.
  356. func (a Address) Bytes() []byte { return a[:] }
  357. // Hash converts an address to a hash by left-padding it with zeros.
  358. func (a Address) Hash() Hash { return BytesToHash(a[:]) }
  359. // Hex returns an EIP55-compliant hex string representation of the address.
  360. func (a Address) Hex() string {
  361. return string(a.checksumHex())
  362. }
  363. // String implements fmt.Stringer.
  364. func (a Address) String() string {
  365. return a.Hex()
  366. }
  367. func (a *Address) checksumHex() []byte {
  368. buf := a.hex()
  369. // compute checksum
  370. sha := sha3.NewLegacyKeccak256()
  371. sha.Write(buf[2:])
  372. hash := sha.Sum(nil)
  373. for i := 2; i < len(buf); i++ {
  374. hashByte := hash[(i-2)/2]
  375. if i%2 == 0 {
  376. hashByte = hashByte >> 4
  377. } else {
  378. hashByte &= 0xf
  379. }
  380. if buf[i] > '9' && hashByte > 7 {
  381. buf[i] -= 32
  382. }
  383. }
  384. return buf[:]
  385. }
  386. func (a Address) hex() []byte {
  387. var buf [len(a)*2 + 2]byte
  388. copy(buf[:2], "0x")
  389. hex.Encode(buf[2:], a[:])
  390. return buf[:]
  391. }
  392. // Format implements fmt.Formatter.
  393. // Address supports the %v, %s, %v, %x, %X and %d format verbs.
  394. func (a Address) Format(s fmt.State, c rune) {
  395. switch c {
  396. case 'v', 's':
  397. s.Write(a.checksumHex())
  398. case 'q':
  399. q := []byte{'"'}
  400. s.Write(q)
  401. s.Write(a.checksumHex())
  402. s.Write(q)
  403. case 'x', 'X':
  404. // %x disables the checksum.
  405. hex := a.hex()
  406. if !s.Flag('#') {
  407. hex = hex[2:]
  408. }
  409. if c == 'X' {
  410. hex = bytes.ToUpper(hex)
  411. }
  412. s.Write(hex)
  413. case 'd':
  414. fmt.Fprint(s, ([len(a)]byte)(a))
  415. default:
  416. fmt.Fprintf(s, "%%!%c(address=%x)", c, a)
  417. }
  418. }
  419. // SetBytes sets the address to the value of b.
  420. // If b is larger than len(a), b will be cropped from the left.
  421. func (a *Address) SetBytes(b []byte) {
  422. if len(b) > len(a) {
  423. b = b[len(b)-AddressLength:]
  424. }
  425. copy(a[AddressLength-len(b):], b)
  426. }
  427. // MarshalText returns the hex representation of a.
  428. func (a Address) MarshalText() ([]byte, error) {
  429. return hexutil.Bytes(a[:]).MarshalText()
  430. }
  431. // UnmarshalText parses a hash in hex syntax.
  432. func (a *Address) UnmarshalText(input []byte) error {
  433. return hexutil.UnmarshalFixedText("Address", input, a[:])
  434. }
  435. // UnmarshalJSON parses a hash in hex syntax.
  436. func (a *Address) UnmarshalJSON(input []byte) error {
  437. return hexutil.UnmarshalFixedJSON(addressT, input, a[:])
  438. }
  439. // Scan implements Scanner for database/sql.
  440. func (a *Address) Scan(src interface{}) error {
  441. srcB, ok := src.([]byte)
  442. if !ok {
  443. return fmt.Errorf("can't scan %T into Address", src)
  444. }
  445. if len(srcB) != AddressLength {
  446. return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength)
  447. }
  448. copy(a[:], srcB)
  449. return nil
  450. }
  451. // Value implements valuer for database/sql.
  452. func (a Address) Value() (driver.Value, error) {
  453. return a[:], nil
  454. }
  455. // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.
  456. func (a Address) ImplementsGraphQLType(name string) bool { return name == "Address" }
  457. // UnmarshalGraphQL unmarshals the provided GraphQL query data.
  458. func (a *Address) UnmarshalGraphQL(input interface{}) error {
  459. var err error
  460. switch input := input.(type) {
  461. case string:
  462. err = a.UnmarshalText([]byte(input))
  463. default:
  464. err = fmt.Errorf("unexpected type %T for Address", input)
  465. }
  466. return err
  467. }
  468. // UnprefixedAddress allows marshaling an Address without 0x prefix.
  469. type UnprefixedAddress Address
  470. // UnmarshalText decodes the address from hex. The 0x prefix is optional.
  471. func (a *UnprefixedAddress) UnmarshalText(input []byte) error {
  472. return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:])
  473. }
  474. // MarshalText encodes the address as hex.
  475. func (a UnprefixedAddress) MarshalText() ([]byte, error) {
  476. return []byte(hex.EncodeToString(a[:])), nil
  477. }
  478. // MixedcaseAddress retains the original string, which may or may not be
  479. // correctly checksummed
  480. type MixedcaseAddress struct {
  481. addr Address
  482. original string
  483. }
  484. // NewMixedcaseAddress constructor (mainly for testing)
  485. func NewMixedcaseAddress(addr Address) MixedcaseAddress {
  486. return MixedcaseAddress{addr: addr, original: addr.Hex()}
  487. }
  488. // NewMixedcaseAddressFromString is mainly meant for unit-testing
  489. func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error) {
  490. if !IsHexAddress(hexaddr) {
  491. return nil, errors.New("invalid address")
  492. }
  493. a := FromHex(hexaddr)
  494. return &MixedcaseAddress{addr: BytesToAddress(a), original: hexaddr}, nil
  495. }
  496. // UnmarshalJSON parses MixedcaseAddress
  497. func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error {
  498. if err := hexutil.UnmarshalFixedJSON(addressT, input, ma.addr[:]); err != nil {
  499. return err
  500. }
  501. return json.Unmarshal(input, &ma.original)
  502. }
  503. // MarshalJSON marshals the original value
  504. func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error) {
  505. if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") {
  506. return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:]))
  507. }
  508. return json.Marshal(fmt.Sprintf("0x%s", ma.original))
  509. }
  510. // Address returns the address
  511. func (ma *MixedcaseAddress) Address() Address {
  512. return ma.addr
  513. }
  514. // String implements fmt.Stringer
  515. func (ma *MixedcaseAddress) String() string {
  516. if ma.ValidChecksum() {
  517. return fmt.Sprintf("%s [chksum ok]", ma.original)
  518. }
  519. return fmt.Sprintf("%s [chksum INVALID]", ma.original)
  520. }
  521. // ValidChecksum returns true if the address has valid checksum
  522. func (ma *MixedcaseAddress) ValidChecksum() bool {
  523. return ma.original == ma.addr.Hex()
  524. }
  525. // Original returns the mixed-case input string
  526. func (ma *MixedcaseAddress) Original() string {
  527. return ma.original
  528. }
  529. type DecryptRequest struct {
  530. SenderKey []byte `json:"senderKey"`
  531. CipherText []byte `json:"cipherText"`
  532. CipherTextNonce []byte `json:"cipherTextNonce"`
  533. RecipientBoxes []string `json:"recipientBoxes"`
  534. RecipientNonce []byte `json:"recipientNonce"`
  535. RecipientKeys []string `json:"recipientKeys"`
  536. }