chunk.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Copyright 2019 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 chunk
  17. import (
  18. "context"
  19. "errors"
  20. "fmt"
  21. "github.com/ethereum/go-ethereum/common"
  22. )
  23. const (
  24. DefaultSize = 4096
  25. MaxPO = 16
  26. AddressLength = 32
  27. )
  28. var (
  29. ErrChunkNotFound = errors.New("chunk not found")
  30. ErrChunkInvalid = errors.New("invalid chunk")
  31. )
  32. type Chunk interface {
  33. Address() Address
  34. Data() []byte
  35. }
  36. type chunk struct {
  37. addr Address
  38. sdata []byte
  39. }
  40. func NewChunk(addr Address, data []byte) Chunk {
  41. return &chunk{
  42. addr: addr,
  43. sdata: data,
  44. }
  45. }
  46. func (c *chunk) Address() Address {
  47. return c.addr
  48. }
  49. func (c *chunk) Data() []byte {
  50. return c.sdata
  51. }
  52. func (self *chunk) String() string {
  53. return fmt.Sprintf("Address: %v Chunksize: %v", self.addr.Log(), len(self.sdata))
  54. }
  55. type Address []byte
  56. var ZeroAddr = Address(common.Hash{}.Bytes())
  57. func (a Address) Hex() string {
  58. return fmt.Sprintf("%064x", []byte(a[:]))
  59. }
  60. func (a Address) Log() string {
  61. if len(a[:]) < 8 {
  62. return fmt.Sprintf("%x", []byte(a[:]))
  63. }
  64. return fmt.Sprintf("%016x", []byte(a[:8]))
  65. }
  66. func (a Address) String() string {
  67. return fmt.Sprintf("%064x", []byte(a))
  68. }
  69. func (a Address) MarshalJSON() (out []byte, err error) {
  70. return []byte(`"` + a.String() + `"`), nil
  71. }
  72. func (a *Address) UnmarshalJSON(value []byte) error {
  73. s := string(value)
  74. *a = make([]byte, 32)
  75. h := common.Hex2Bytes(s[1 : len(s)-1])
  76. copy(*a, h)
  77. return nil
  78. }
  79. // Proximity returns the proximity order of the MSB distance between x and y
  80. //
  81. // The distance metric MSB(x, y) of two equal length byte sequences x an y is the
  82. // value of the binary integer cast of the x^y, ie., x and y bitwise xor-ed.
  83. // the binary cast is big endian: most significant bit first (=MSB).
  84. //
  85. // Proximity(x, y) is a discrete logarithmic scaling of the MSB distance.
  86. // It is defined as the reverse rank of the integer part of the base 2
  87. // logarithm of the distance.
  88. // It is calculated by counting the number of common leading zeros in the (MSB)
  89. // binary representation of the x^y.
  90. //
  91. // (0 farthest, 255 closest, 256 self)
  92. func Proximity(one, other []byte) (ret int) {
  93. b := (MaxPO-1)/8 + 1
  94. if b > len(one) {
  95. b = len(one)
  96. }
  97. m := 8
  98. for i := 0; i < b; i++ {
  99. oxo := one[i] ^ other[i]
  100. for j := 0; j < m; j++ {
  101. if (oxo>>uint8(7-j))&0x01 != 0 {
  102. return i*8 + j
  103. }
  104. }
  105. }
  106. return MaxPO
  107. }
  108. // ModeGet enumerates different Getter modes.
  109. type ModeGet int
  110. func (m ModeGet) String() string {
  111. switch m {
  112. case ModeGetRequest:
  113. return "Request"
  114. case ModeGetSync:
  115. return "Sync"
  116. case ModeGetLookup:
  117. return "Lookup"
  118. default:
  119. return "Unknown"
  120. }
  121. }
  122. // Getter modes.
  123. const (
  124. // ModeGetRequest: when accessed for retrieval
  125. ModeGetRequest ModeGet = iota
  126. // ModeGetSync: when accessed for syncing or proof of custody request
  127. ModeGetSync
  128. // ModeGetLookup: when accessed to lookup a a chunk in feeds or other places
  129. ModeGetLookup
  130. )
  131. // ModePut enumerates different Putter modes.
  132. type ModePut int
  133. func (m ModePut) String() string {
  134. switch m {
  135. case ModePutRequest:
  136. return "Request"
  137. case ModePutSync:
  138. return "Sync"
  139. case ModePutUpload:
  140. return "Upload"
  141. default:
  142. return "Unknown"
  143. }
  144. }
  145. // Putter modes.
  146. const (
  147. // ModePutRequest: when a chunk is received as a result of retrieve request and delivery
  148. ModePutRequest ModePut = iota
  149. // ModePutSync: when a chunk is received via syncing
  150. ModePutSync
  151. // ModePutUpload: when a chunk is created by local upload
  152. ModePutUpload
  153. )
  154. // ModeSet enumerates different Setter modes.
  155. type ModeSet int
  156. func (m ModeSet) String() string {
  157. switch m {
  158. case ModeSetAccess:
  159. return "Access"
  160. case ModeSetSync:
  161. return "Sync"
  162. case ModeSetRemove:
  163. return "Remove"
  164. default:
  165. return "Unknown"
  166. }
  167. }
  168. // Setter modes.
  169. const (
  170. // ModeSetAccess: when an update request is received for a chunk or chunk is retrieved for delivery
  171. ModeSetAccess ModeSet = iota
  172. // ModeSetSync: when a chunk is added to a pull sync batch or when a push sync receipt is received
  173. ModeSetSync
  174. // ModeSetRemove: when a chunk is removed
  175. ModeSetRemove
  176. )
  177. // Descriptor holds information required for Pull syncing. This struct
  178. // is provided by subscribing to pull index.
  179. type Descriptor struct {
  180. Address Address
  181. BinID uint64
  182. }
  183. func (d *Descriptor) String() string {
  184. if d == nil {
  185. return ""
  186. }
  187. return fmt.Sprintf("%s bin id %v", d.Address.Hex(), d.BinID)
  188. }
  189. type Store interface {
  190. Get(ctx context.Context, mode ModeGet, addr Address) (ch Chunk, err error)
  191. Put(ctx context.Context, mode ModePut, ch Chunk) (exists bool, err error)
  192. Has(ctx context.Context, addr Address) (yes bool, err error)
  193. Set(ctx context.Context, mode ModeSet, addr Address) (err error)
  194. LastPullSubscriptionBinID(bin uint8) (id uint64, err error)
  195. SubscribePull(ctx context.Context, bin uint8, since, until uint64) (c <-chan Descriptor, stop func())
  196. Close() (err error)
  197. }
  198. // Validator validates a chunk.
  199. type Validator interface {
  200. Validate(ch Chunk) bool
  201. }
  202. // ValidatorStore encapsulates Store by decorting the Put method
  203. // with validators check.
  204. type ValidatorStore struct {
  205. Store
  206. validators []Validator
  207. }
  208. // NewValidatorStore returns a new ValidatorStore which uses
  209. // provided validators to validate chunks on Put.
  210. func NewValidatorStore(store Store, validators ...Validator) (s *ValidatorStore) {
  211. return &ValidatorStore{
  212. Store: store,
  213. validators: validators,
  214. }
  215. }
  216. // Put overrides Store put method with validators check. If one of the validators
  217. // return true, the chunk is considered valid and Store Put method is called.
  218. // If all validators return false, ErrChunkInvalid is returned.
  219. func (s *ValidatorStore) Put(ctx context.Context, mode ModePut, ch Chunk) (exists bool, err error) {
  220. for _, v := range s.validators {
  221. if v.Validate(ch) {
  222. return s.Store.Put(ctx, mode, ch)
  223. }
  224. }
  225. return false, ErrChunkInvalid
  226. }