github.com/ethersphere/bee/v2@v2.2.0/pkg/feeds/putter.go (about)

     1  // Copyright 2021 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package feeds
     6  
     7  import (
     8  	"context"
     9  	"encoding/binary"
    10  
    11  	"github.com/ethersphere/bee/v2/pkg/cac"
    12  	"github.com/ethersphere/bee/v2/pkg/crypto"
    13  	"github.com/ethersphere/bee/v2/pkg/soc"
    14  	storage "github.com/ethersphere/bee/v2/pkg/storage"
    15  	"github.com/ethersphere/bee/v2/pkg/swarm"
    16  )
    17  
    18  // Updater is the generic interface f
    19  type Updater interface {
    20  	Update(ctx context.Context, at int64, payload []byte) error
    21  	Feed() *Feed
    22  }
    23  
    24  // Putter encapsulates a chunk store putter and a Feed to store feed updates
    25  type Putter struct {
    26  	putter storage.Putter
    27  	signer crypto.Signer
    28  	*Feed
    29  }
    30  
    31  // NewPutter constructs a feed Putter
    32  func NewPutter(putter storage.Putter, signer crypto.Signer, topic []byte) (*Putter, error) {
    33  	owner, err := signer.EthereumAddress()
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	feed := New(topic, owner)
    38  	return &Putter{putter, signer, feed}, nil
    39  }
    40  
    41  // Put pushes an update to the feed through the chunk stores
    42  func (u *Putter) Put(ctx context.Context, i Index, at int64, payload []byte) error {
    43  	id, err := u.Feed.Update(i).Id()
    44  	if err != nil {
    45  		return err
    46  	}
    47  	cac, err := toChunk(uint64(at), payload)
    48  	if err != nil {
    49  		return err
    50  	}
    51  	s := soc.New(id, cac)
    52  	ch, err := s.Sign(u.signer)
    53  	if err != nil {
    54  		return err
    55  	}
    56  	return u.putter.Put(ctx, ch)
    57  }
    58  
    59  func toChunk(at uint64, payload []byte) (swarm.Chunk, error) {
    60  	ts := make([]byte, 8)
    61  	binary.BigEndian.PutUint64(ts, at)
    62  	return cac.New(append(ts, payload...))
    63  }