Common.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file Common.h
  15. * @author Alex Leverington <nessence@gmail.com>
  16. * @author Gav Wood <i@gavwood.com>
  17. * @date 2014
  18. *
  19. * Ethereum-specific data structures & algorithms.
  20. */
  21. #pragma once
  22. #include <mutex>
  23. #include <libdevcore/Common.h>
  24. #include <libdevcore/FixedHash.h>
  25. #include <libdevcore/Exceptions.h>
  26. #include <libdevcore/FileSystem.h>
  27. namespace dev
  28. {
  29. using Secret = SecureFixedHash<32>;
  30. /// A public key: 64 bytes.
  31. /// @NOTE This is not endian-specific; it's just a bunch of bytes.
  32. using Public = h512;
  33. /// A signature: 65 bytes: r: [0, 32), s: [32, 64), v: 64.
  34. /// @NOTE This is not endian-specific; it's just a bunch of bytes.
  35. using Signature = h520;
  36. struct SignatureStruct
  37. {
  38. SignatureStruct() = default;
  39. SignatureStruct(Signature const& _s) { *(h520*)this = _s; }
  40. SignatureStruct(h256 const& _r, h256 const& _s, byte _v): r(_r), s(_s), v(_v) {}
  41. operator Signature() const { return *(h520 const*)this; }
  42. /// @returns true if r,s,v values are valid, otherwise false
  43. bool isValid() const noexcept;
  44. /// @returns the public part of the key that signed @a _hash to give this sig.
  45. Public recover(h256 const& _hash) const;
  46. h256 r;
  47. h256 s;
  48. byte v = 0;
  49. };
  50. /// An Ethereum address: 20 bytes.
  51. /// @NOTE This is not endian-specific; it's just a bunch of bytes.
  52. using Address = h160;
  53. /// The zero address.
  54. extern Address ZeroAddress;
  55. /// A vector of Ethereum addresses.
  56. using Addresses = h160s;
  57. /// A hash set of Ethereum addresses.
  58. using AddressHash = std::unordered_set<h160>;
  59. /// A vector of secrets.
  60. using Secrets = std::vector<Secret>;
  61. /// Convert a secret key into the public key equivalent.
  62. Public toPublic(Secret const& _secret);
  63. /// Convert a public key to address.
  64. Address toAddress(Public const& _public);
  65. /// Convert a secret key into address of public key equivalent.
  66. /// @returns 0 if it's not a valid secret key.
  67. Address toAddress(Secret const& _secret);
  68. // Convert transaction from and nonce to address.
  69. Address toAddress(Address const& _from, u256 const& _nonce);
  70. /// Encrypts plain text using Public key.
  71. void encrypt(Public const& _k, bytesConstRef _plain, bytes& o_cipher);
  72. /// Decrypts cipher using Secret key.
  73. bool decrypt(Secret const& _k, bytesConstRef _cipher, bytes& o_plaintext);
  74. /// Symmetric encryption.
  75. void encryptSym(Secret const& _k, bytesConstRef _plain, bytes& o_cipher);
  76. /// Symmetric decryption.
  77. bool decryptSym(Secret const& _k, bytesConstRef _cipher, bytes& o_plaintext);
  78. /// Encrypt payload using ECIES standard with AES128-CTR.
  79. void encryptECIES(Public const& _k, bytesConstRef _plain, bytes& o_cipher);
  80. /// Encrypt payload using ECIES standard with AES128-CTR.
  81. /// @a _sharedMacData is shared authenticated data.
  82. void encryptECIES(Public const& _k, bytesConstRef _sharedMacData, bytesConstRef _plain, bytes& o_cipher);
  83. /// Decrypt payload using ECIES standard with AES128-CTR.
  84. bool decryptECIES(Secret const& _k, bytesConstRef _cipher, bytes& o_plaintext);
  85. /// Decrypt payload using ECIES standard with AES128-CTR.
  86. /// @a _sharedMacData is shared authenticated data.
  87. bool decryptECIES(Secret const& _k, bytesConstRef _sharedMacData, bytesConstRef _cipher, bytes& o_plaintext);
  88. /// Encrypts payload with random IV/ctr using AES128-CTR.
  89. std::pair<bytes, h128> encryptSymNoAuth(SecureFixedHash<16> const& _k, bytesConstRef _plain);
  90. /// Encrypts payload with specified IV/ctr using AES128-CTR.
  91. bytes encryptAES128CTR(bytesConstRef _k, h128 const& _iv, bytesConstRef _plain);
  92. /// Decrypts payload with specified IV/ctr using AES128-CTR.
  93. bytesSec decryptAES128CTR(bytesConstRef _k, h128 const& _iv, bytesConstRef _cipher);
  94. /// Encrypts payload with specified IV/ctr using AES128-CTR.
  95. inline bytes encryptSymNoAuth(SecureFixedHash<16> const& _k, h128 const& _iv, bytesConstRef _plain) { return encryptAES128CTR(_k.ref(), _iv, _plain); }
  96. inline bytes encryptSymNoAuth(SecureFixedHash<32> const& _k, h128 const& _iv, bytesConstRef _plain) { return encryptAES128CTR(_k.ref(), _iv, _plain); }
  97. /// Decrypts payload with specified IV/ctr using AES128-CTR.
  98. inline bytesSec decryptSymNoAuth(SecureFixedHash<16> const& _k, h128 const& _iv, bytesConstRef _cipher) { return decryptAES128CTR(_k.ref(), _iv, _cipher); }
  99. inline bytesSec decryptSymNoAuth(SecureFixedHash<32> const& _k, h128 const& _iv, bytesConstRef _cipher) { return decryptAES128CTR(_k.ref(), _iv, _cipher); }
  100. /// Recovers Public key from signed message hash.
  101. Public recover(Signature const& _sig, h256 const& _hash);
  102. /// Returns siganture of message hash.
  103. Signature sign(Secret const& _k, h256 const& _hash);
  104. /// Verify signature.
  105. bool verify(Public const& _k, Signature const& _s, h256 const& _hash);
  106. /// Derive key via PBKDF2.
  107. bytesSec pbkdf2(std::string const& _pass, bytes const& _salt, unsigned _iterations, unsigned _dkLen = 32);
  108. /// Derive key via Scrypt.
  109. bytesSec scrypt(std::string const& _pass, bytes const& _salt, uint64_t _n, uint32_t _r, uint32_t _p, unsigned _dkLen);
  110. /// Simple class that represents a "key pair".
  111. /// All of the data of the class can be regenerated from the secret key (m_secret) alone.
  112. /// Actually stores a tuplet of secret, public and address (the right 160-bits of the public).
  113. class KeyPair
  114. {
  115. public:
  116. /// Null constructor.
  117. KeyPair() {}
  118. /// Normal constructor - populates object from the given secret key.
  119. KeyPair(Secret const& _k) { populateFromSecret(_k); }
  120. /// Create a new, randomly generated object.
  121. static KeyPair create();
  122. /// Create from an encrypted seed.
  123. static KeyPair fromEncryptedSeed(bytesConstRef _seed, std::string const& _password);
  124. /// Retrieve the secret key.
  125. Secret const& secret() const { return m_secret; }
  126. /// Retrieve the secret key.
  127. Secret const& sec() const { return m_secret; }
  128. /// Retrieve the public key.
  129. Public const& pub() const { return m_public; }
  130. /// Retrieve the associated address of the public key.
  131. Address const& address() const { return m_address; }
  132. bool operator==(KeyPair const& _c) const { return m_public == _c.m_public; }
  133. bool operator!=(KeyPair const& _c) const { return m_public != _c.m_public; }
  134. private:
  135. void populateFromSecret(Secret const& _k);
  136. Secret m_secret;
  137. Public m_public;
  138. Address m_address;
  139. };
  140. namespace crypto
  141. {
  142. DEV_SIMPLE_EXCEPTION(InvalidState);
  143. /// Key derivation
  144. h256 kdf(Secret const& _priv, h256 const& _hash);
  145. /**
  146. * @brief Generator for non-repeating nonce material.
  147. * The Nonce class should only be used when a non-repeating nonce
  148. * is required and, in its current form, not recommended for signatures.
  149. * This is primarily because the key-material for signatures is
  150. * encrypted on disk whereas the seed for Nonce is not.
  151. * Thus, Nonce's primary intended use at this time is for networking
  152. * where the key is also stored in plaintext.
  153. */
  154. class Nonce
  155. {
  156. public:
  157. /// Returns the next nonce (might be read from a file).
  158. static Secret get() { static Nonce s; return s.next(); }
  159. private:
  160. Nonce() = default;
  161. /// @returns the next nonce.
  162. Secret next();
  163. std::mutex x_value;
  164. Secret m_value;
  165. };
  166. }
  167. }