Skip to content

Commit f023394

Browse files
janosnonsense
authored andcommitted
swarm/chunk: move chunk related declarations to chunk package (#19170)
1 parent b7e0dec commit f023394

28 files changed

+324
-285
lines changed

swarm/chunk/chunk.go

Lines changed: 105 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,109 @@
11
package chunk
22

3+
import (
4+
"errors"
5+
"fmt"
6+
7+
"github.com/ethereum/go-ethereum/common"
8+
)
9+
310
const (
4-
DefaultSize = 4096
11+
DefaultSize = 4096
12+
MaxPO = 16
13+
AddressLength = 32
14+
)
15+
16+
var (
17+
ErrChunkNotFound = errors.New("chunk not found")
18+
ErrChunkInvalid = errors.New("invalid chunk")
519
)
20+
21+
type Chunk interface {
22+
Address() Address
23+
Data() []byte
24+
}
25+
26+
type chunk struct {
27+
addr Address
28+
sdata []byte
29+
}
30+
31+
func NewChunk(addr Address, data []byte) *chunk {
32+
return &chunk{
33+
addr: addr,
34+
sdata: data,
35+
}
36+
}
37+
38+
func (c *chunk) Address() Address {
39+
return c.addr
40+
}
41+
42+
func (c *chunk) Data() []byte {
43+
return c.sdata
44+
}
45+
46+
func (self *chunk) String() string {
47+
return fmt.Sprintf("Address: %v Chunksize: %v", self.addr.Log(), len(self.sdata))
48+
}
49+
50+
type Address []byte
51+
52+
var ZeroAddr = Address(common.Hash{}.Bytes())
53+
54+
func (a Address) Hex() string {
55+
return fmt.Sprintf("%064x", []byte(a[:]))
56+
}
57+
58+
func (a Address) Log() string {
59+
if len(a[:]) < 8 {
60+
return fmt.Sprintf("%x", []byte(a[:]))
61+
}
62+
return fmt.Sprintf("%016x", []byte(a[:8]))
63+
}
64+
65+
func (a Address) String() string {
66+
return fmt.Sprintf("%064x", []byte(a))
67+
}
68+
69+
func (a Address) MarshalJSON() (out []byte, err error) {
70+
return []byte(`"` + a.String() + `"`), nil
71+
}
72+
73+
func (a *Address) UnmarshalJSON(value []byte) error {
74+
s := string(value)
75+
*a = make([]byte, 32)
76+
h := common.Hex2Bytes(s[1 : len(s)-1])
77+
copy(*a, h)
78+
return nil
79+
}
80+
81+
// Proximity returns the proximity order of the MSB distance between x and y
82+
//
83+
// The distance metric MSB(x, y) of two equal length byte sequences x an y is the
84+
// value of the binary integer cast of the x^y, ie., x and y bitwise xor-ed.
85+
// the binary cast is big endian: most significant bit first (=MSB).
86+
//
87+
// Proximity(x, y) is a discrete logarithmic scaling of the MSB distance.
88+
// It is defined as the reverse rank of the integer part of the base 2
89+
// logarithm of the distance.
90+
// It is calculated by counting the number of common leading zeros in the (MSB)
91+
// binary representation of the x^y.
92+
//
93+
// (0 farthest, 255 closest, 256 self)
94+
func Proximity(one, other []byte) (ret int) {
95+
b := (MaxPO-1)/8 + 1
96+
if b > len(one) {
97+
b = len(one)
98+
}
99+
m := 8
100+
for i := 0; i < b; i++ {
101+
oxo := one[i] ^ other[i]
102+
for j := 0; j < m; j++ {
103+
if (oxo>>uint8(7-j))&0x01 != 0 {
104+
return i*8 + j
105+
}
106+
}
107+
}
108+
return MaxPO
109+
}

swarm/storage/types_test.go renamed to swarm/chunk/proximity_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
// You should have received a copy of the GNU Lesser General Public License
1515
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
1616

17-
package storage
17+
package chunk
1818

1919
import (
2020
"strconv"

swarm/storage/chunker.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import (
2525
"time"
2626

2727
"github.com/ethereum/go-ethereum/metrics"
28-
ch "github.com/ethereum/go-ethereum/swarm/chunk"
28+
"github.com/ethereum/go-ethereum/swarm/chunk"
2929
"github.com/ethereum/go-ethereum/swarm/log"
3030
"github.com/ethereum/go-ethereum/swarm/spancontext"
3131
opentracing "github.com/opentracing/opentracing-go"
@@ -127,7 +127,7 @@ type TreeChunker struct {
127127
func TreeJoin(ctx context.Context, addr Address, getter Getter, depth int) *LazyChunkReader {
128128
jp := &JoinerParams{
129129
ChunkerParams: ChunkerParams{
130-
chunkSize: ch.DefaultSize,
130+
chunkSize: chunk.DefaultSize,
131131
hashSize: int64(len(addr)),
132132
},
133133
addr: addr,
@@ -147,7 +147,7 @@ func TreeSplit(ctx context.Context, data io.Reader, size int64, putter Putter) (
147147
tsp := &TreeSplitterParams{
148148
SplitterParams: SplitterParams{
149149
ChunkerParams: ChunkerParams{
150-
chunkSize: ch.DefaultSize,
150+
chunkSize: chunk.DefaultSize,
151151
hashSize: putter.RefSize(),
152152
},
153153
reader: data,

swarm/storage/common_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import (
2929
"time"
3030

3131
"github.com/ethereum/go-ethereum/log"
32-
ch "github.com/ethereum/go-ethereum/swarm/chunk"
32+
"github.com/ethereum/go-ethereum/swarm/chunk"
3333
"github.com/mattn/go-colorable"
3434
)
3535

@@ -94,7 +94,7 @@ func mput(store ChunkStore, n int, f func(i int64) Chunk) (hs []Chunk, err error
9494
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
9595
defer cancel()
9696
for i := int64(0); i < int64(n); i++ {
97-
chunk := f(ch.DefaultSize)
97+
chunk := f(chunk.DefaultSize)
9898
go func() {
9999
select {
100100
case errc <- store.Put(ctx, chunk):

swarm/storage/error.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,7 @@
1616

1717
package storage
1818

19-
import (
20-
"errors"
21-
)
19+
import "github.com/ethereum/go-ethereum/swarm/chunk"
2220

2321
const (
2422
ErrInit = iota
@@ -31,7 +29,8 @@ const (
3129
ErrNotSynced
3230
)
3331

32+
// Errors are the same as the ones in chunk package for backward compatibility.
3433
var (
35-
ErrChunkNotFound = errors.New("chunk not found")
36-
ErrChunkInvalid = errors.New("invalid chunk")
34+
ErrChunkNotFound = chunk.ErrChunkNotFound
35+
ErrChunkInvalid = chunk.ErrChunkNotFound
3736
)

swarm/storage/hasherstore.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import (
2121
"fmt"
2222
"sync/atomic"
2323

24-
ch "github.com/ethereum/go-ethereum/swarm/chunk"
24+
"github.com/ethereum/go-ethereum/swarm/chunk"
2525
"github.com/ethereum/go-ethereum/swarm/storage/encryption"
2626
"golang.org/x/crypto/sha3"
2727
)
@@ -156,7 +156,7 @@ func (h *hasherStore) createHash(chunkData ChunkData) Address {
156156
return hasher.Sum(nil)
157157
}
158158

159-
func (h *hasherStore) createChunk(chunkData ChunkData) *chunk {
159+
func (h *hasherStore) createChunk(chunkData ChunkData) Chunk {
160160
hash := h.createHash(chunkData)
161161
chunk := NewChunk(hash, chunkData)
162162
return chunk
@@ -189,9 +189,9 @@ func (h *hasherStore) decryptChunkData(chunkData ChunkData, encryptionKey encryp
189189

190190
// removing extra bytes which were just added for padding
191191
length := ChunkData(decryptedSpan).Size()
192-
for length > ch.DefaultSize {
193-
length = length + (ch.DefaultSize - 1)
194-
length = length / ch.DefaultSize
192+
for length > chunk.DefaultSize {
193+
length = length + (chunk.DefaultSize - 1)
194+
length = length / chunk.DefaultSize
195195
length *= uint64(h.refSize)
196196
}
197197

@@ -232,14 +232,14 @@ func (h *hasherStore) decrypt(chunkData ChunkData, key encryption.Key) ([]byte,
232232
}
233233

234234
func (h *hasherStore) newSpanEncryption(key encryption.Key) encryption.Encryption {
235-
return encryption.New(key, 0, uint32(ch.DefaultSize/h.refSize), sha3.NewLegacyKeccak256)
235+
return encryption.New(key, 0, uint32(chunk.DefaultSize/h.refSize), sha3.NewLegacyKeccak256)
236236
}
237237

238238
func (h *hasherStore) newDataEncryption(key encryption.Key) encryption.Encryption {
239-
return encryption.New(key, int(ch.DefaultSize), 0, sha3.NewLegacyKeccak256)
239+
return encryption.New(key, int(chunk.DefaultSize), 0, sha3.NewLegacyKeccak256)
240240
}
241241

242-
func (h *hasherStore) storeChunk(ctx context.Context, chunk *chunk) {
242+
func (h *hasherStore) storeChunk(ctx context.Context, chunk Chunk) {
243243
atomic.AddUint64(&h.nrChunks, 1)
244244
go func() {
245245
select {

swarm/storage/ldbstore.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ func decodeIndex(data []byte, index *dpaDBIndex) error {
312312
return dec.Decode(index)
313313
}
314314

315-
func decodeData(addr Address, data []byte) (*chunk, error) {
315+
func decodeData(addr Address, data []byte) (Chunk, error) {
316316
return NewChunk(addr, data[32:]), nil
317317
}
318318

@@ -502,7 +502,7 @@ func (s *LDBStore) Import(in io.Reader) (int64, error) {
502502
}
503503

504504
// Cleanup iterates over the database and deletes chunks if they pass the `f` condition
505-
func (s *LDBStore) Cleanup(f func(*chunk) bool) {
505+
func (s *LDBStore) Cleanup(f func(Chunk) bool) {
506506
var errorsFound, removed, total int
507507

508508
it := s.db.NewIterator()
@@ -551,12 +551,14 @@ func (s *LDBStore) Cleanup(f func(*chunk) bool) {
551551
continue
552552
}
553553

554-
cs := int64(binary.LittleEndian.Uint64(c.sdata[:8]))
555-
log.Trace("chunk", "key", fmt.Sprintf("%x", key), "ck", fmt.Sprintf("%x", ck), "dkey", fmt.Sprintf("%x", datakey), "dataidx", index.Idx, "po", po, "len data", len(data), "len sdata", len(c.sdata), "size", cs)
554+
sdata := c.Data()
555+
556+
cs := int64(binary.LittleEndian.Uint64(sdata[:8]))
557+
log.Trace("chunk", "key", fmt.Sprintf("%x", key), "ck", fmt.Sprintf("%x", ck), "dkey", fmt.Sprintf("%x", datakey), "dataidx", index.Idx, "po", po, "len data", len(data), "len sdata", len(sdata), "size", cs)
556558

557559
// if chunk is to be removed
558560
if f(c) {
559-
log.Warn("chunk for cleanup", "key", fmt.Sprintf("%x", key), "ck", fmt.Sprintf("%x", ck), "dkey", fmt.Sprintf("%x", datakey), "dataidx", index.Idx, "po", po, "len data", len(data), "len sdata", len(c.sdata), "size", cs)
561+
log.Warn("chunk for cleanup", "key", fmt.Sprintf("%x", key), "ck", fmt.Sprintf("%x", ck), "dkey", fmt.Sprintf("%x", datakey), "dataidx", index.Idx, "po", po, "len data", len(data), "len sdata", len(sdata), "size", cs)
560562
s.deleteNow(&index, getIndexKey(key[1:]), po)
561563
removed++
562564
errorsFound++
@@ -980,7 +982,7 @@ func (s *LDBStore) Has(_ context.Context, addr Address) bool {
980982
}
981983

982984
// TODO: To conform with other private methods of this object indices should not be updated
983-
func (s *LDBStore) get(addr Address) (chunk *chunk, err error) {
985+
func (s *LDBStore) get(addr Address) (chunk Chunk, err error) {
984986
if s.closed {
985987
return nil, ErrDBClosed
986988
}

swarm/storage/ldbstore_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import (
2828
"testing"
2929

3030
"github.com/ethereum/go-ethereum/common"
31-
ch "github.com/ethereum/go-ethereum/swarm/chunk"
31+
"github.com/ethereum/go-ethereum/swarm/chunk"
3232
"github.com/ethereum/go-ethereum/swarm/log"
3333
"github.com/ethereum/go-ethereum/swarm/storage/mock/mem"
3434
ldberrors "github.com/syndtr/goleveldb/leveldb/errors"
@@ -103,7 +103,7 @@ func TestMarkAccessed(t *testing.T) {
103103
t.Fatalf("init dbStore failed: %v", err)
104104
}
105105

106-
h := GenerateRandomChunk(ch.DefaultSize)
106+
h := GenerateRandomChunk(chunk.DefaultSize)
107107

108108
db.Put(context.Background(), h)
109109

@@ -201,7 +201,7 @@ func testIterator(t *testing.T, mock bool) {
201201
t.Fatalf("init dbStore failed: %v", err)
202202
}
203203

204-
chunks := GenerateRandomChunks(ch.DefaultSize, chunkcount)
204+
chunks := GenerateRandomChunks(chunk.DefaultSize, chunkcount)
205205

206206
for i = 0; i < len(chunks); i++ {
207207
chunkkeys[i] = chunks[i].Address()
@@ -468,7 +468,7 @@ func testLDBStoreRemoveThenCollectGarbage(t *testing.T) {
468468
// put capacity count number of chunks
469469
chunks := make([]Chunk, n)
470470
for i := 0; i < n; i++ {
471-
c := GenerateRandomChunk(ch.DefaultSize)
471+
c := GenerateRandomChunk(chunk.DefaultSize)
472472
chunks[i] = c
473473
log.Trace("generate random chunk", "idx", i, "chunk", c)
474474
}

swarm/storage/localstore.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ func (ls *LocalStore) Migrate() error {
241241
func (ls *LocalStore) migrateFromNoneToPurity() {
242242
// delete chunks that are not valid, i.e. chunks that do not pass
243243
// any of the ls.Validators
244-
ls.DbStore.Cleanup(func(c *chunk) bool {
244+
ls.DbStore.Cleanup(func(c Chunk) bool {
245245
return !ls.isValid(c)
246246
})
247247
}

0 commit comments

Comments
 (0)