You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

296 lines
6.1 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package types
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "sync"
  7. "github.com/pkg/errors"
  8. "github.com/tendermint/tendermint/crypto/merkle"
  9. cmn "github.com/tendermint/tendermint/libs/common"
  10. )
  11. var (
  12. ErrPartSetUnexpectedIndex = errors.New("Error part set unexpected index")
  13. ErrPartSetInvalidProof = errors.New("Error part set invalid proof")
  14. )
  15. type Part struct {
  16. Index int `json:"index"`
  17. Bytes cmn.HexBytes `json:"bytes"`
  18. Proof merkle.SimpleProof `json:"proof"`
  19. // Cache
  20. hash []byte
  21. }
  22. // ValidateBasic performs basic validation.
  23. func (part *Part) ValidateBasic() error {
  24. if part.Index < 0 {
  25. return errors.New("Negative Index")
  26. }
  27. if len(part.Bytes) > BlockPartSizeBytes {
  28. return fmt.Errorf("Too big (max: %d)", BlockPartSizeBytes)
  29. }
  30. return nil
  31. }
  32. func (part *Part) String() string {
  33. return part.StringIndented("")
  34. }
  35. func (part *Part) StringIndented(indent string) string {
  36. return fmt.Sprintf(`Part{#%v
  37. %s Bytes: %X...
  38. %s Proof: %v
  39. %s}`,
  40. part.Index,
  41. indent, cmn.Fingerprint(part.Bytes),
  42. indent, part.Proof.StringIndented(indent+" "),
  43. indent)
  44. }
  45. //-------------------------------------
  46. type PartSetHeader struct {
  47. Total int `json:"total"`
  48. Hash cmn.HexBytes `json:"hash"`
  49. }
  50. func (psh PartSetHeader) String() string {
  51. return fmt.Sprintf("%v:%X", psh.Total, cmn.Fingerprint(psh.Hash))
  52. }
  53. func (psh PartSetHeader) IsZero() bool {
  54. return psh.Total == 0 && len(psh.Hash) == 0
  55. }
  56. func (psh PartSetHeader) Equals(other PartSetHeader) bool {
  57. return psh.Total == other.Total && bytes.Equal(psh.Hash, other.Hash)
  58. }
  59. // ValidateBasic performs basic validation.
  60. func (psh PartSetHeader) ValidateBasic() error {
  61. if psh.Total < 0 {
  62. return errors.New("Negative Total")
  63. }
  64. // Hash can be empty in case of POLBlockID.PartsHeader in Proposal.
  65. if err := ValidateHash(psh.Hash); err != nil {
  66. return errors.Wrap(err, "Wrong Hash")
  67. }
  68. return nil
  69. }
  70. //-------------------------------------
  71. type PartSet struct {
  72. total int
  73. hash []byte
  74. mtx sync.Mutex
  75. parts []*Part
  76. partsBitArray *cmn.BitArray
  77. count int
  78. }
  79. // Returns an immutable, full PartSet from the data bytes.
  80. // The data bytes are split into "partSize" chunks, and merkle tree computed.
  81. func NewPartSetFromData(data []byte, partSize int) *PartSet {
  82. // divide data into 4kb parts.
  83. total := (len(data) + partSize - 1) / partSize
  84. parts := make([]*Part, total)
  85. partsBytes := make([][]byte, total)
  86. partsBitArray := cmn.NewBitArray(total)
  87. for i := 0; i < total; i++ {
  88. part := &Part{
  89. Index: i,
  90. Bytes: data[i*partSize : cmn.MinInt(len(data), (i+1)*partSize)],
  91. }
  92. parts[i] = part
  93. partsBytes[i] = part.Bytes
  94. partsBitArray.SetIndex(i, true)
  95. }
  96. // Compute merkle proofs
  97. root, proofs := merkle.SimpleProofsFromByteSlices(partsBytes)
  98. for i := 0; i < total; i++ {
  99. parts[i].Proof = *proofs[i]
  100. }
  101. return &PartSet{
  102. total: total,
  103. hash: root,
  104. parts: parts,
  105. partsBitArray: partsBitArray,
  106. count: total,
  107. }
  108. }
  109. // Returns an empty PartSet ready to be populated.
  110. func NewPartSetFromHeader(header PartSetHeader) *PartSet {
  111. return &PartSet{
  112. total: header.Total,
  113. hash: header.Hash,
  114. parts: make([]*Part, header.Total),
  115. partsBitArray: cmn.NewBitArray(header.Total),
  116. count: 0,
  117. }
  118. }
  119. func (ps *PartSet) Header() PartSetHeader {
  120. if ps == nil {
  121. return PartSetHeader{}
  122. }
  123. return PartSetHeader{
  124. Total: ps.total,
  125. Hash: ps.hash,
  126. }
  127. }
  128. func (ps *PartSet) HasHeader(header PartSetHeader) bool {
  129. if ps == nil {
  130. return false
  131. }
  132. return ps.Header().Equals(header)
  133. }
  134. func (ps *PartSet) BitArray() *cmn.BitArray {
  135. ps.mtx.Lock()
  136. defer ps.mtx.Unlock()
  137. return ps.partsBitArray.Copy()
  138. }
  139. func (ps *PartSet) Hash() []byte {
  140. if ps == nil {
  141. return nil
  142. }
  143. return ps.hash
  144. }
  145. func (ps *PartSet) HashesTo(hash []byte) bool {
  146. if ps == nil {
  147. return false
  148. }
  149. return bytes.Equal(ps.hash, hash)
  150. }
  151. func (ps *PartSet) Count() int {
  152. if ps == nil {
  153. return 0
  154. }
  155. return ps.count
  156. }
  157. func (ps *PartSet) Total() int {
  158. if ps == nil {
  159. return 0
  160. }
  161. return ps.total
  162. }
  163. func (ps *PartSet) AddPart(part *Part) (bool, error) {
  164. if ps == nil {
  165. return false, nil
  166. }
  167. ps.mtx.Lock()
  168. defer ps.mtx.Unlock()
  169. // Invalid part index
  170. if part.Index >= ps.total {
  171. return false, ErrPartSetUnexpectedIndex
  172. }
  173. // If part already exists, return false.
  174. if ps.parts[part.Index] != nil {
  175. return false, nil
  176. }
  177. // Check hash proof
  178. if part.Proof.Verify(ps.Hash(), part.Bytes) != nil {
  179. return false, ErrPartSetInvalidProof
  180. }
  181. // Add part
  182. ps.parts[part.Index] = part
  183. ps.partsBitArray.SetIndex(part.Index, true)
  184. ps.count++
  185. return true, nil
  186. }
  187. func (ps *PartSet) GetPart(index int) *Part {
  188. ps.mtx.Lock()
  189. defer ps.mtx.Unlock()
  190. return ps.parts[index]
  191. }
  192. func (ps *PartSet) IsComplete() bool {
  193. return ps.count == ps.total
  194. }
  195. func (ps *PartSet) GetReader() io.Reader {
  196. if !ps.IsComplete() {
  197. cmn.PanicSanity("Cannot GetReader() on incomplete PartSet")
  198. }
  199. return NewPartSetReader(ps.parts)
  200. }
  201. type PartSetReader struct {
  202. i int
  203. parts []*Part
  204. reader *bytes.Reader
  205. }
  206. func NewPartSetReader(parts []*Part) *PartSetReader {
  207. return &PartSetReader{
  208. i: 0,
  209. parts: parts,
  210. reader: bytes.NewReader(parts[0].Bytes),
  211. }
  212. }
  213. func (psr *PartSetReader) Read(p []byte) (n int, err error) {
  214. readerLen := psr.reader.Len()
  215. if readerLen >= len(p) {
  216. return psr.reader.Read(p)
  217. } else if readerLen > 0 {
  218. n1, err := psr.Read(p[:readerLen])
  219. if err != nil {
  220. return n1, err
  221. }
  222. n2, err := psr.Read(p[readerLen:])
  223. return n1 + n2, err
  224. }
  225. psr.i++
  226. if psr.i >= len(psr.parts) {
  227. return 0, io.EOF
  228. }
  229. psr.reader = bytes.NewReader(psr.parts[psr.i].Bytes)
  230. return psr.Read(p)
  231. }
  232. func (ps *PartSet) StringShort() string {
  233. if ps == nil {
  234. return "nil-PartSet"
  235. }
  236. ps.mtx.Lock()
  237. defer ps.mtx.Unlock()
  238. return fmt.Sprintf("(%v of %v)", ps.Count(), ps.Total())
  239. }
  240. func (ps *PartSet) MarshalJSON() ([]byte, error) {
  241. if ps == nil {
  242. return []byte("{}"), nil
  243. }
  244. ps.mtx.Lock()
  245. defer ps.mtx.Unlock()
  246. return cdc.MarshalJSON(struct {
  247. CountTotal string `json:"count/total"`
  248. PartsBitArray *cmn.BitArray `json:"parts_bit_array"`
  249. }{
  250. fmt.Sprintf("%d/%d", ps.Count(), ps.Total()),
  251. ps.partsBitArray,
  252. })
  253. }