hasherstore.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // Copyright 2018 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 storage
  17. import (
  18. "context"
  19. "fmt"
  20. "sync"
  21. "github.com/ethereum/go-ethereum/crypto/sha3"
  22. "github.com/ethereum/go-ethereum/swarm/storage/encryption"
  23. )
  24. type chunkEncryption struct {
  25. spanEncryption encryption.Encryption
  26. dataEncryption encryption.Encryption
  27. }
  28. type hasherStore struct {
  29. store ChunkStore
  30. hashFunc SwarmHasher
  31. chunkEncryption *chunkEncryption
  32. hashSize int // content hash size
  33. refSize int64 // reference size (content hash + possibly encryption key)
  34. wg *sync.WaitGroup
  35. closed chan struct{}
  36. }
  37. func newChunkEncryption(chunkSize, refSize int64) *chunkEncryption {
  38. return &chunkEncryption{
  39. spanEncryption: encryption.New(0, uint32(chunkSize/refSize), sha3.NewKeccak256),
  40. dataEncryption: encryption.New(int(chunkSize), 0, sha3.NewKeccak256),
  41. }
  42. }
  43. // NewHasherStore creates a hasherStore object, which implements Putter and Getter interfaces.
  44. // With the HasherStore you can put and get chunk data (which is just []byte) into a ChunkStore
  45. // and the hasherStore will take core of encryption/decryption of data if necessary
  46. func NewHasherStore(chunkStore ChunkStore, hashFunc SwarmHasher, toEncrypt bool) *hasherStore {
  47. var chunkEncryption *chunkEncryption
  48. hashSize := hashFunc().Size()
  49. refSize := int64(hashSize)
  50. if toEncrypt {
  51. refSize += encryption.KeyLength
  52. chunkEncryption = newChunkEncryption(DefaultChunkSize, refSize)
  53. }
  54. return &hasherStore{
  55. store: chunkStore,
  56. hashFunc: hashFunc,
  57. chunkEncryption: chunkEncryption,
  58. hashSize: hashSize,
  59. refSize: refSize,
  60. wg: &sync.WaitGroup{},
  61. closed: make(chan struct{}),
  62. }
  63. }
  64. // Put stores the chunkData into the ChunkStore of the hasherStore and returns the reference.
  65. // If hasherStore has a chunkEncryption object, the data will be encrypted.
  66. // Asynchronous function, the data will not necessarily be stored when it returns.
  67. func (h *hasherStore) Put(chunkData ChunkData) (Reference, error) {
  68. c := chunkData
  69. size := chunkData.Size()
  70. var encryptionKey encryption.Key
  71. if h.chunkEncryption != nil {
  72. var err error
  73. c, encryptionKey, err = h.encryptChunkData(chunkData)
  74. if err != nil {
  75. return nil, err
  76. }
  77. }
  78. chunk := h.createChunk(c, size)
  79. h.storeChunk(chunk)
  80. return Reference(append(chunk.Addr, encryptionKey...)), nil
  81. }
  82. // Get returns data of the chunk with the given reference (retrieved from the ChunkStore of hasherStore).
  83. // If the data is encrypted and the reference contains an encryption key, it will be decrypted before
  84. // return.
  85. func (h *hasherStore) Get(ref Reference) (ChunkData, error) {
  86. key, encryptionKey, err := parseReference(ref, h.hashSize)
  87. if err != nil {
  88. return nil, err
  89. }
  90. toDecrypt := (encryptionKey != nil)
  91. chunk, err := h.store.Get(key)
  92. if err != nil {
  93. return nil, err
  94. }
  95. chunkData := chunk.SData
  96. if toDecrypt {
  97. var err error
  98. chunkData, err = h.decryptChunkData(chunkData, encryptionKey)
  99. if err != nil {
  100. return nil, err
  101. }
  102. }
  103. return chunkData, nil
  104. }
  105. // Close indicates that no more chunks will be put with the hasherStore, so the Wait
  106. // function can return when all the previously put chunks has been stored.
  107. func (h *hasherStore) Close() {
  108. close(h.closed)
  109. }
  110. // Wait returns when
  111. // 1) the Close() function has been called and
  112. // 2) all the chunks which has been Put has been stored
  113. func (h *hasherStore) Wait(ctx context.Context) error {
  114. <-h.closed
  115. h.wg.Wait()
  116. return nil
  117. }
  118. func (h *hasherStore) createHash(chunkData ChunkData) Address {
  119. hasher := h.hashFunc()
  120. hasher.ResetWithLength(chunkData[:8]) // 8 bytes of length
  121. hasher.Write(chunkData[8:]) // minus 8 []byte length
  122. return hasher.Sum(nil)
  123. }
  124. func (h *hasherStore) createChunk(chunkData ChunkData, chunkSize int64) *Chunk {
  125. hash := h.createHash(chunkData)
  126. chunk := NewChunk(hash, nil)
  127. chunk.SData = chunkData
  128. chunk.Size = chunkSize
  129. return chunk
  130. }
  131. func (h *hasherStore) encryptChunkData(chunkData ChunkData) (ChunkData, encryption.Key, error) {
  132. if len(chunkData) < 8 {
  133. return nil, nil, fmt.Errorf("Invalid ChunkData, min length 8 got %v", len(chunkData))
  134. }
  135. encryptionKey, err := encryption.GenerateRandomKey()
  136. if err != nil {
  137. return nil, nil, err
  138. }
  139. encryptedSpan, err := h.chunkEncryption.spanEncryption.Encrypt(chunkData[:8], encryptionKey)
  140. if err != nil {
  141. return nil, nil, err
  142. }
  143. encryptedData, err := h.chunkEncryption.dataEncryption.Encrypt(chunkData[8:], encryptionKey)
  144. if err != nil {
  145. return nil, nil, err
  146. }
  147. c := make(ChunkData, len(encryptedSpan)+len(encryptedData))
  148. copy(c[:8], encryptedSpan)
  149. copy(c[8:], encryptedData)
  150. return c, encryptionKey, nil
  151. }
  152. func (h *hasherStore) decryptChunkData(chunkData ChunkData, encryptionKey encryption.Key) (ChunkData, error) {
  153. if len(chunkData) < 8 {
  154. return nil, fmt.Errorf("Invalid ChunkData, min length 8 got %v", len(chunkData))
  155. }
  156. decryptedSpan, err := h.chunkEncryption.spanEncryption.Decrypt(chunkData[:8], encryptionKey)
  157. if err != nil {
  158. return nil, err
  159. }
  160. decryptedData, err := h.chunkEncryption.dataEncryption.Decrypt(chunkData[8:], encryptionKey)
  161. if err != nil {
  162. return nil, err
  163. }
  164. // removing extra bytes which were just added for padding
  165. length := ChunkData(decryptedSpan).Size()
  166. for length > DefaultChunkSize {
  167. length = length + (DefaultChunkSize - 1)
  168. length = length / DefaultChunkSize
  169. length *= h.refSize
  170. }
  171. c := make(ChunkData, length+8)
  172. copy(c[:8], decryptedSpan)
  173. copy(c[8:], decryptedData[:length])
  174. return c[:length+8], nil
  175. }
  176. func (h *hasherStore) RefSize() int64 {
  177. return h.refSize
  178. }
  179. func (h *hasherStore) storeChunk(chunk *Chunk) {
  180. h.wg.Add(1)
  181. go func() {
  182. <-chunk.dbStoredC
  183. h.wg.Done()
  184. }()
  185. h.store.Put(chunk)
  186. }
  187. func parseReference(ref Reference, hashSize int) (Address, encryption.Key, error) {
  188. encryptedKeyLength := hashSize + encryption.KeyLength
  189. switch len(ref) {
  190. case KeyLength:
  191. return Address(ref), nil, nil
  192. case encryptedKeyLength:
  193. encKeyIdx := len(ref) - encryption.KeyLength
  194. return Address(ref[:encKeyIdx]), encryption.Key(ref[encKeyIdx:]), nil
  195. default:
  196. return nil, nil, fmt.Errorf("Invalid reference length, expected %v or %v got %v", hashSize, encryptedKeyLength, len(ref))
  197. }
  198. }