hasherstore.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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/atomic"
  21. ch "github.com/ethereum/go-ethereum/swarm/chunk"
  22. "github.com/ethereum/go-ethereum/swarm/storage/encryption"
  23. "golang.org/x/crypto/sha3"
  24. )
  25. type hasherStore struct {
  26. store ChunkStore
  27. toEncrypt bool
  28. hashFunc SwarmHasher
  29. hashSize int // content hash size
  30. refSize int64 // reference size (content hash + possibly encryption key)
  31. errC chan error // global error channel
  32. doneC chan struct{} // closed by Close() call to indicate that count is the final number of chunks
  33. quitC chan struct{} // closed to quit unterminated routines
  34. // nrChunks is used with atomic functions
  35. // it is required to be at the end of the struct to ensure 64bit alignment for arm architecture
  36. // see: https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  37. nrChunks uint64 // number of chunks to store
  38. }
  39. // NewHasherStore creates a hasherStore object, which implements Putter and Getter interfaces.
  40. // With the HasherStore you can put and get chunk data (which is just []byte) into a ChunkStore
  41. // and the hasherStore will take core of encryption/decryption of data if necessary
  42. func NewHasherStore(store ChunkStore, hashFunc SwarmHasher, toEncrypt bool) *hasherStore {
  43. hashSize := hashFunc().Size()
  44. refSize := int64(hashSize)
  45. if toEncrypt {
  46. refSize += encryption.KeyLength
  47. }
  48. h := &hasherStore{
  49. store: store,
  50. toEncrypt: toEncrypt,
  51. hashFunc: hashFunc,
  52. hashSize: hashSize,
  53. refSize: refSize,
  54. errC: make(chan error),
  55. doneC: make(chan struct{}),
  56. quitC: make(chan struct{}),
  57. }
  58. return h
  59. }
  60. // Put stores the chunkData into the ChunkStore of the hasherStore and returns the reference.
  61. // If hasherStore has a chunkEncryption object, the data will be encrypted.
  62. // Asynchronous function, the data will not necessarily be stored when it returns.
  63. func (h *hasherStore) Put(ctx context.Context, chunkData ChunkData) (Reference, error) {
  64. c := chunkData
  65. var encryptionKey encryption.Key
  66. if h.toEncrypt {
  67. var err error
  68. c, encryptionKey, err = h.encryptChunkData(chunkData)
  69. if err != nil {
  70. return nil, err
  71. }
  72. }
  73. chunk := h.createChunk(c)
  74. h.storeChunk(ctx, chunk)
  75. return Reference(append(chunk.Address(), encryptionKey...)), nil
  76. }
  77. // Get returns data of the chunk with the given reference (retrieved from the ChunkStore of hasherStore).
  78. // If the data is encrypted and the reference contains an encryption key, it will be decrypted before
  79. // return.
  80. func (h *hasherStore) Get(ctx context.Context, ref Reference) (ChunkData, error) {
  81. addr, encryptionKey, err := parseReference(ref, h.hashSize)
  82. if err != nil {
  83. return nil, err
  84. }
  85. chunk, err := h.store.Get(ctx, addr)
  86. if err != nil {
  87. return nil, err
  88. }
  89. chunkData := ChunkData(chunk.Data())
  90. toDecrypt := (encryptionKey != nil)
  91. if toDecrypt {
  92. var err error
  93. chunkData, err = h.decryptChunkData(chunkData, encryptionKey)
  94. if err != nil {
  95. return nil, err
  96. }
  97. }
  98. return chunkData, nil
  99. }
  100. // Close indicates that no more chunks will be put with the hasherStore, so the Wait
  101. // function can return when all the previously put chunks has been stored.
  102. func (h *hasherStore) Close() {
  103. close(h.doneC)
  104. }
  105. // Wait returns when
  106. // 1) the Close() function has been called and
  107. // 2) all the chunks which has been Put has been stored
  108. func (h *hasherStore) Wait(ctx context.Context) error {
  109. defer close(h.quitC)
  110. var nrStoredChunks uint64 // number of stored chunks
  111. var done bool
  112. doneC := h.doneC
  113. for {
  114. select {
  115. // if context is done earlier, just return with the error
  116. case <-ctx.Done():
  117. return ctx.Err()
  118. // doneC is closed if all chunks have been submitted, from then we just wait until all of them are also stored
  119. case <-doneC:
  120. done = true
  121. doneC = nil
  122. // a chunk has been stored, if err is nil, then successfully, so increase the stored chunk counter
  123. case err := <-h.errC:
  124. if err != nil {
  125. return err
  126. }
  127. nrStoredChunks++
  128. }
  129. // if all the chunks have been submitted and all of them are stored, then we can return
  130. if done {
  131. if nrStoredChunks >= atomic.LoadUint64(&h.nrChunks) {
  132. return nil
  133. }
  134. }
  135. }
  136. }
  137. func (h *hasherStore) createHash(chunkData ChunkData) Address {
  138. hasher := h.hashFunc()
  139. hasher.ResetWithLength(chunkData[:8]) // 8 bytes of length
  140. hasher.Write(chunkData[8:]) // minus 8 []byte length
  141. return hasher.Sum(nil)
  142. }
  143. func (h *hasherStore) createChunk(chunkData ChunkData) *chunk {
  144. hash := h.createHash(chunkData)
  145. chunk := NewChunk(hash, chunkData)
  146. return chunk
  147. }
  148. func (h *hasherStore) encryptChunkData(chunkData ChunkData) (ChunkData, encryption.Key, error) {
  149. if len(chunkData) < 8 {
  150. return nil, nil, fmt.Errorf("Invalid ChunkData, min length 8 got %v", len(chunkData))
  151. }
  152. key, encryptedSpan, encryptedData, err := h.encrypt(chunkData)
  153. if err != nil {
  154. return nil, nil, err
  155. }
  156. c := make(ChunkData, len(encryptedSpan)+len(encryptedData))
  157. copy(c[:8], encryptedSpan)
  158. copy(c[8:], encryptedData)
  159. return c, key, nil
  160. }
  161. func (h *hasherStore) decryptChunkData(chunkData ChunkData, encryptionKey encryption.Key) (ChunkData, error) {
  162. if len(chunkData) < 8 {
  163. return nil, fmt.Errorf("Invalid ChunkData, min length 8 got %v", len(chunkData))
  164. }
  165. decryptedSpan, decryptedData, err := h.decrypt(chunkData, encryptionKey)
  166. if err != nil {
  167. return nil, err
  168. }
  169. // removing extra bytes which were just added for padding
  170. length := ChunkData(decryptedSpan).Size()
  171. for length > ch.DefaultSize {
  172. length = length + (ch.DefaultSize - 1)
  173. length = length / ch.DefaultSize
  174. length *= uint64(h.refSize)
  175. }
  176. c := make(ChunkData, length+8)
  177. copy(c[:8], decryptedSpan)
  178. copy(c[8:], decryptedData[:length])
  179. return c, nil
  180. }
  181. func (h *hasherStore) RefSize() int64 {
  182. return h.refSize
  183. }
  184. func (h *hasherStore) encrypt(chunkData ChunkData) (encryption.Key, []byte, []byte, error) {
  185. key := encryption.GenerateRandomKey(encryption.KeyLength)
  186. encryptedSpan, err := h.newSpanEncryption(key).Encrypt(chunkData[:8])
  187. if err != nil {
  188. return nil, nil, nil, err
  189. }
  190. encryptedData, err := h.newDataEncryption(key).Encrypt(chunkData[8:])
  191. if err != nil {
  192. return nil, nil, nil, err
  193. }
  194. return key, encryptedSpan, encryptedData, nil
  195. }
  196. func (h *hasherStore) decrypt(chunkData ChunkData, key encryption.Key) ([]byte, []byte, error) {
  197. encryptedSpan, err := h.newSpanEncryption(key).Encrypt(chunkData[:8])
  198. if err != nil {
  199. return nil, nil, err
  200. }
  201. encryptedData, err := h.newDataEncryption(key).Encrypt(chunkData[8:])
  202. if err != nil {
  203. return nil, nil, err
  204. }
  205. return encryptedSpan, encryptedData, nil
  206. }
  207. func (h *hasherStore) newSpanEncryption(key encryption.Key) encryption.Encryption {
  208. return encryption.New(key, 0, uint32(ch.DefaultSize/h.refSize), sha3.NewLegacyKeccak256)
  209. }
  210. func (h *hasherStore) newDataEncryption(key encryption.Key) encryption.Encryption {
  211. return encryption.New(key, int(ch.DefaultSize), 0, sha3.NewLegacyKeccak256)
  212. }
  213. func (h *hasherStore) storeChunk(ctx context.Context, chunk *chunk) {
  214. atomic.AddUint64(&h.nrChunks, 1)
  215. go func() {
  216. select {
  217. case h.errC <- h.store.Put(ctx, chunk):
  218. case <-h.quitC:
  219. }
  220. }()
  221. }
  222. func parseReference(ref Reference, hashSize int) (Address, encryption.Key, error) {
  223. encryptedRefLength := hashSize + encryption.KeyLength
  224. switch len(ref) {
  225. case AddressLength:
  226. return Address(ref), nil, nil
  227. case encryptedRefLength:
  228. encKeyIdx := len(ref) - encryption.KeyLength
  229. return Address(ref[:encKeyIdx]), encryption.Key(ref[encKeyIdx:]), nil
  230. default:
  231. return nil, nil, fmt.Errorf("Invalid reference length, expected %v or %v got %v", hashSize, encryptedRefLength, len(ref))
  232. }
  233. }