request.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 feed
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "hash"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/common/hexutil"
  23. "github.com/ethereum/go-ethereum/swarm/storage"
  24. "github.com/ethereum/go-ethereum/swarm/storage/feed/lookup"
  25. )
  26. // Request represents a request to sign or signed feed update message
  27. type Request struct {
  28. Update // actual content that will be put on the chunk, less signature
  29. Signature *Signature
  30. idAddr storage.Address // cached chunk address for the update (not serialized, for internal use)
  31. binaryData []byte // cached serialized data (does not get serialized again!, for efficiency/internal use)
  32. }
  33. // updateRequestJSON represents a JSON-serialized UpdateRequest
  34. type updateRequestJSON struct {
  35. ID
  36. ProtocolVersion uint8 `json:"protocolVersion"`
  37. Data string `json:"data,omitempty"`
  38. Signature string `json:"signature,omitempty"`
  39. }
  40. // Request layout
  41. // Update bytes
  42. // SignatureLength bytes
  43. const minimumSignedUpdateLength = minimumUpdateDataLength + signatureLength
  44. // NewFirstRequest returns a ready to sign request to publish a first feed update
  45. func NewFirstRequest(topic Topic) *Request {
  46. request := new(Request)
  47. // get the current time
  48. now := TimestampProvider.Now().Time
  49. request.Epoch = lookup.GetFirstEpoch(now)
  50. request.Feed.Topic = topic
  51. request.Header.Version = ProtocolVersion
  52. return request
  53. }
  54. // SetData stores the payload data the feed update will be updated with
  55. func (r *Request) SetData(data []byte) {
  56. r.data = data
  57. r.Signature = nil
  58. }
  59. // IsUpdate returns true if this request models a signed update or otherwise it is a signature request
  60. func (r *Request) IsUpdate() bool {
  61. return r.Signature != nil
  62. }
  63. // Verify checks that signatures are valid
  64. func (r *Request) Verify() (err error) {
  65. if len(r.data) == 0 {
  66. return NewError(ErrInvalidValue, "Update does not contain data")
  67. }
  68. if r.Signature == nil {
  69. return NewError(ErrInvalidSignature, "Missing signature field")
  70. }
  71. digest, err := r.GetDigest()
  72. if err != nil {
  73. return err
  74. }
  75. // get the address of the signer (which also checks that it's a valid signature)
  76. r.Feed.User, err = getUserAddr(digest, *r.Signature)
  77. if err != nil {
  78. return err
  79. }
  80. // check that the lookup information contained in the chunk matches the updateAddr (chunk search key)
  81. // that was used to retrieve this chunk
  82. // if this validation fails, someone forged a chunk.
  83. if !bytes.Equal(r.idAddr, r.Addr()) {
  84. return NewError(ErrInvalidSignature, "Signature address does not match with update user address")
  85. }
  86. return nil
  87. }
  88. // Sign executes the signature to validate the update message
  89. func (r *Request) Sign(signer Signer) error {
  90. r.Feed.User = signer.Address()
  91. r.binaryData = nil //invalidate serialized data
  92. digest, err := r.GetDigest() // computes digest and serializes into .binaryData
  93. if err != nil {
  94. return err
  95. }
  96. signature, err := signer.Sign(digest)
  97. if err != nil {
  98. return err
  99. }
  100. // Although the Signer interface returns the public address of the signer,
  101. // recover it from the signature to see if they match
  102. userAddr, err := getUserAddr(digest, signature)
  103. if err != nil {
  104. return NewError(ErrInvalidSignature, "Error verifying signature")
  105. }
  106. if userAddr != signer.Address() { // sanity check to make sure the Signer is declaring the same address used to sign!
  107. return NewError(ErrInvalidSignature, "Signer address does not match update user address")
  108. }
  109. r.Signature = &signature
  110. r.idAddr = r.Addr()
  111. return nil
  112. }
  113. // GetDigest creates the feed update digest used in signatures
  114. // the serialized payload is cached in .binaryData
  115. func (r *Request) GetDigest() (result common.Hash, err error) {
  116. hasher := hashPool.Get().(hash.Hash)
  117. defer hashPool.Put(hasher)
  118. hasher.Reset()
  119. dataLength := r.Update.binaryLength()
  120. if r.binaryData == nil {
  121. r.binaryData = make([]byte, dataLength+signatureLength)
  122. if err := r.Update.binaryPut(r.binaryData[:dataLength]); err != nil {
  123. return result, err
  124. }
  125. }
  126. hasher.Write(r.binaryData[:dataLength]) //everything except the signature.
  127. return common.BytesToHash(hasher.Sum(nil)), nil
  128. }
  129. // create an update chunk.
  130. func (r *Request) toChunk() (storage.Chunk, error) {
  131. // Check that the update is signed and serialized
  132. // For efficiency, data is serialized during signature and cached in
  133. // the binaryData field when computing the signature digest in .getDigest()
  134. if r.Signature == nil || r.binaryData == nil {
  135. return nil, NewError(ErrInvalidSignature, "toChunk called without a valid signature or payload data. Call .Sign() first.")
  136. }
  137. updateLength := r.Update.binaryLength()
  138. // signature is the last item in the chunk data
  139. copy(r.binaryData[updateLength:], r.Signature[:])
  140. chunk := storage.NewChunk(r.idAddr, r.binaryData)
  141. return chunk, nil
  142. }
  143. // fromChunk populates this structure from chunk data. It does not verify the signature is valid.
  144. func (r *Request) fromChunk(updateAddr storage.Address, chunkdata []byte) error {
  145. // for update chunk layout see Request definition
  146. //deserialize the feed update portion
  147. if err := r.Update.binaryGet(chunkdata[:len(chunkdata)-signatureLength]); err != nil {
  148. return err
  149. }
  150. // Extract the signature
  151. var signature *Signature
  152. cursor := r.Update.binaryLength()
  153. sigdata := chunkdata[cursor : cursor+signatureLength]
  154. if len(sigdata) > 0 {
  155. signature = &Signature{}
  156. copy(signature[:], sigdata)
  157. }
  158. r.Signature = signature
  159. r.idAddr = updateAddr
  160. r.binaryData = chunkdata
  161. return nil
  162. }
  163. // FromValues deserializes this instance from a string key-value store
  164. // useful to parse query strings
  165. func (r *Request) FromValues(values Values, data []byte) error {
  166. signatureBytes, err := hexutil.Decode(values.Get("signature"))
  167. if err != nil {
  168. r.Signature = nil
  169. } else {
  170. if len(signatureBytes) != signatureLength {
  171. return NewError(ErrInvalidSignature, "Incorrect signature length")
  172. }
  173. r.Signature = new(Signature)
  174. copy(r.Signature[:], signatureBytes)
  175. }
  176. err = r.Update.FromValues(values, data)
  177. if err != nil {
  178. return err
  179. }
  180. r.idAddr = r.Addr()
  181. return err
  182. }
  183. // AppendValues serializes this structure into the provided string key-value store
  184. // useful to build query strings
  185. func (r *Request) AppendValues(values Values) []byte {
  186. if r.Signature != nil {
  187. values.Set("signature", hexutil.Encode(r.Signature[:]))
  188. }
  189. return r.Update.AppendValues(values)
  190. }
  191. // fromJSON takes an update request JSON and populates an UpdateRequest
  192. func (r *Request) fromJSON(j *updateRequestJSON) error {
  193. r.ID = j.ID
  194. r.Header.Version = j.ProtocolVersion
  195. var err error
  196. if j.Data != "" {
  197. r.data, err = hexutil.Decode(j.Data)
  198. if err != nil {
  199. return NewError(ErrInvalidValue, "Cannot decode data")
  200. }
  201. }
  202. if j.Signature != "" {
  203. sigBytes, err := hexutil.Decode(j.Signature)
  204. if err != nil || len(sigBytes) != signatureLength {
  205. return NewError(ErrInvalidSignature, "Cannot decode signature")
  206. }
  207. r.Signature = new(Signature)
  208. r.idAddr = r.Addr()
  209. copy(r.Signature[:], sigBytes)
  210. }
  211. return nil
  212. }
  213. // UnmarshalJSON takes a JSON structure stored in a byte array and populates the Request object
  214. // Implements json.Unmarshaler interface
  215. func (r *Request) UnmarshalJSON(rawData []byte) error {
  216. var requestJSON updateRequestJSON
  217. if err := json.Unmarshal(rawData, &requestJSON); err != nil {
  218. return err
  219. }
  220. return r.fromJSON(&requestJSON)
  221. }
  222. // MarshalJSON takes an update request and encodes it as a JSON structure into a byte array
  223. // Implements json.Marshaler interface
  224. func (r *Request) MarshalJSON() (rawData []byte, err error) {
  225. var signatureString, dataString string
  226. if r.Signature != nil {
  227. signatureString = hexutil.Encode(r.Signature[:])
  228. }
  229. if r.data != nil {
  230. dataString = hexutil.Encode(r.data)
  231. }
  232. requestJSON := &updateRequestJSON{
  233. ID: r.ID,
  234. ProtocolVersion: r.Header.Version,
  235. Data: dataString,
  236. Signature: signatureString,
  237. }
  238. return json.Marshal(requestJSON)
  239. }