github.com/ethersphere/bee/v2@v2.2.0/pkg/settlement/swap/headers/utilities.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 swap
     6  
     7  import (
     8  	"errors"
     9  	"math/big"
    10  
    11  	"github.com/ethersphere/bee/v2/pkg/p2p"
    12  )
    13  
    14  const (
    15  	exchangeRateFieldName = "exchange"
    16  	deductionFieldName    = "deduction"
    17  )
    18  
    19  var (
    20  	// ErrFieldLength denotes p2p.Header having malformed field length in bytes
    21  	ErrFieldLength = errors.New("field length error")
    22  	// ErrNoExchangeHeader denotes p2p.Header lacking specified field
    23  	ErrNoExchangeHeader = errors.New("no exchange header")
    24  	// ErrNoDeductionHeader denotes p2p.Header lacking specified field
    25  	ErrNoDeductionHeader = errors.New("no deduction header")
    26  )
    27  
    28  func MakeSettlementHeaders(exchangeRate, deduction *big.Int) p2p.Headers {
    29  
    30  	return p2p.Headers{
    31  		exchangeRateFieldName: exchangeRate.Bytes(),
    32  		deductionFieldName:    deduction.Bytes(),
    33  	}
    34  }
    35  
    36  func ParseSettlementResponseHeaders(receivedHeaders p2p.Headers) (exchange, deduction *big.Int, err error) {
    37  
    38  	exchangeRate, err := ParseExchangeHeader(receivedHeaders)
    39  	if err != nil {
    40  		return nil, nil, err
    41  	}
    42  
    43  	deduction, err = ParseDeductionHeader(receivedHeaders)
    44  	if err != nil {
    45  		return exchangeRate, nil, err
    46  	}
    47  
    48  	return exchangeRate, deduction, nil
    49  }
    50  
    51  func ParseExchangeHeader(receivedHeaders p2p.Headers) (*big.Int, error) {
    52  	if receivedHeaders[exchangeRateFieldName] == nil {
    53  		return nil, ErrNoExchangeHeader
    54  	}
    55  
    56  	exchange := new(big.Int).SetBytes(receivedHeaders[exchangeRateFieldName])
    57  	return exchange, nil
    58  }
    59  
    60  func ParseDeductionHeader(receivedHeaders p2p.Headers) (*big.Int, error) {
    61  	if receivedHeaders[deductionFieldName] == nil {
    62  		return nil, ErrNoDeductionHeader
    63  	}
    64  
    65  	deduced := new(big.Int).SetBytes(receivedHeaders[deductionFieldName])
    66  	return deduced, nil
    67  }