github.com/maynardminer/ethereumprogpow@v1.8.23/whisper/whisperv6/envelope.go (about)

     1  // Copyright 2016 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  
    17  // Contains the Whisper protocol Envelope element.
    18  
    19  package whisperv6
    20  
    21  import (
    22  	"crypto/ecdsa"
    23  	"encoding/binary"
    24  	"fmt"
    25  	gmath "math"
    26  	"math/big"
    27  	"time"
    28  
    29  	"github.com/ethereumprogpow/ethereumprogpow/common"
    30  	"github.com/ethereumprogpow/ethereumprogpow/common/math"
    31  	"github.com/ethereumprogpow/ethereumprogpow/crypto"
    32  	"github.com/ethereumprogpow/ethereumprogpow/crypto/ecies"
    33  	"github.com/ethereumprogpow/ethereumprogpow/rlp"
    34  )
    35  
    36  // Envelope represents a clear-text data packet to transmit through the Whisper
    37  // network. Its contents may or may not be encrypted and signed.
    38  type Envelope struct {
    39  	Expiry uint32
    40  	TTL    uint32
    41  	Topic  TopicType
    42  	Data   []byte
    43  	Nonce  uint64
    44  
    45  	pow float64 // Message-specific PoW as described in the Whisper specification.
    46  
    47  	// the following variables should not be accessed directly, use the corresponding function instead: Hash(), Bloom()
    48  	hash  common.Hash // Cached hash of the envelope to avoid rehashing every time.
    49  	bloom []byte
    50  }
    51  
    52  // size returns the size of envelope as it is sent (i.e. public fields only)
    53  func (e *Envelope) size() int {
    54  	return EnvelopeHeaderLength + len(e.Data)
    55  }
    56  
    57  // rlpWithoutNonce returns the RLP encoded envelope contents, except the nonce.
    58  func (e *Envelope) rlpWithoutNonce() []byte {
    59  	res, _ := rlp.EncodeToBytes([]interface{}{e.Expiry, e.TTL, e.Topic, e.Data})
    60  	return res
    61  }
    62  
    63  // NewEnvelope wraps a Whisper message with expiration and destination data
    64  // included into an envelope for network forwarding.
    65  func NewEnvelope(ttl uint32, topic TopicType, msg *sentMessage) *Envelope {
    66  	env := Envelope{
    67  		Expiry: uint32(time.Now().Add(time.Second * time.Duration(ttl)).Unix()),
    68  		TTL:    ttl,
    69  		Topic:  topic,
    70  		Data:   msg.Raw,
    71  		Nonce:  0,
    72  	}
    73  
    74  	return &env
    75  }
    76  
    77  // Seal closes the envelope by spending the requested amount of time as a proof
    78  // of work on hashing the data.
    79  func (e *Envelope) Seal(options *MessageParams) error {
    80  	if options.PoW == 0 {
    81  		// PoW is not required
    82  		return nil
    83  	}
    84  
    85  	var target, bestBit int
    86  	if options.PoW < 0 {
    87  		// target is not set - the function should run for a period
    88  		// of time specified in WorkTime param. Since we can predict
    89  		// the execution time, we can also adjust Expiry.
    90  		e.Expiry += options.WorkTime
    91  	} else {
    92  		target = e.powToFirstBit(options.PoW)
    93  	}
    94  
    95  	buf := make([]byte, 64)
    96  	h := crypto.Keccak256(e.rlpWithoutNonce())
    97  	copy(buf[:32], h)
    98  
    99  	finish := time.Now().Add(time.Duration(options.WorkTime) * time.Second).UnixNano()
   100  	for nonce := uint64(0); time.Now().UnixNano() < finish; {
   101  		for i := 0; i < 1024; i++ {
   102  			binary.BigEndian.PutUint64(buf[56:], nonce)
   103  			d := new(big.Int).SetBytes(crypto.Keccak256(buf))
   104  			firstBit := math.FirstBitSet(d)
   105  			if firstBit > bestBit {
   106  				e.Nonce, bestBit = nonce, firstBit
   107  				if target > 0 && bestBit >= target {
   108  					return nil
   109  				}
   110  			}
   111  			nonce++
   112  		}
   113  	}
   114  
   115  	if target > 0 && bestBit < target {
   116  		return fmt.Errorf("failed to reach the PoW target, specified pow time (%d seconds) was insufficient", options.WorkTime)
   117  	}
   118  
   119  	return nil
   120  }
   121  
   122  // PoW computes (if necessary) and returns the proof of work target
   123  // of the envelope.
   124  func (e *Envelope) PoW() float64 {
   125  	if e.pow == 0 {
   126  		e.calculatePoW(0)
   127  	}
   128  	return e.pow
   129  }
   130  
   131  func (e *Envelope) calculatePoW(diff uint32) {
   132  	buf := make([]byte, 64)
   133  	h := crypto.Keccak256(e.rlpWithoutNonce())
   134  	copy(buf[:32], h)
   135  	binary.BigEndian.PutUint64(buf[56:], e.Nonce)
   136  	d := new(big.Int).SetBytes(crypto.Keccak256(buf))
   137  	firstBit := math.FirstBitSet(d)
   138  	x := gmath.Pow(2, float64(firstBit))
   139  	x /= float64(e.size())
   140  	x /= float64(e.TTL + diff)
   141  	e.pow = x
   142  }
   143  
   144  func (e *Envelope) powToFirstBit(pow float64) int {
   145  	x := pow
   146  	x *= float64(e.size())
   147  	x *= float64(e.TTL)
   148  	bits := gmath.Log2(x)
   149  	bits = gmath.Ceil(bits)
   150  	res := int(bits)
   151  	if res < 1 {
   152  		res = 1
   153  	}
   154  	return res
   155  }
   156  
   157  // Hash returns the SHA3 hash of the envelope, calculating it if not yet done.
   158  func (e *Envelope) Hash() common.Hash {
   159  	if (e.hash == common.Hash{}) {
   160  		encoded, _ := rlp.EncodeToBytes(e)
   161  		e.hash = crypto.Keccak256Hash(encoded)
   162  	}
   163  	return e.hash
   164  }
   165  
   166  // DecodeRLP decodes an Envelope from an RLP data stream.
   167  func (e *Envelope) DecodeRLP(s *rlp.Stream) error {
   168  	raw, err := s.Raw()
   169  	if err != nil {
   170  		return err
   171  	}
   172  	// The decoding of Envelope uses the struct fields but also needs
   173  	// to compute the hash of the whole RLP-encoded envelope. This
   174  	// type has the same structure as Envelope but is not an
   175  	// rlp.Decoder (does not implement DecodeRLP function).
   176  	// Only public members will be encoded.
   177  	type rlpenv Envelope
   178  	if err := rlp.DecodeBytes(raw, (*rlpenv)(e)); err != nil {
   179  		return err
   180  	}
   181  	e.hash = crypto.Keccak256Hash(raw)
   182  	return nil
   183  }
   184  
   185  // OpenAsymmetric tries to decrypt an envelope, potentially encrypted with a particular key.
   186  func (e *Envelope) OpenAsymmetric(key *ecdsa.PrivateKey) (*ReceivedMessage, error) {
   187  	message := &ReceivedMessage{Raw: e.Data}
   188  	err := message.decryptAsymmetric(key)
   189  	switch err {
   190  	case nil:
   191  		return message, nil
   192  	case ecies.ErrInvalidPublicKey: // addressed to somebody else
   193  		return nil, err
   194  	default:
   195  		return nil, fmt.Errorf("unable to open envelope, decrypt failed: %v", err)
   196  	}
   197  }
   198  
   199  // OpenSymmetric tries to decrypt an envelope, potentially encrypted with a particular key.
   200  func (e *Envelope) OpenSymmetric(key []byte) (msg *ReceivedMessage, err error) {
   201  	msg = &ReceivedMessage{Raw: e.Data}
   202  	err = msg.decryptSymmetric(key)
   203  	if err != nil {
   204  		msg = nil
   205  	}
   206  	return msg, err
   207  }
   208  
   209  // Open tries to decrypt an envelope, and populates the message fields in case of success.
   210  func (e *Envelope) Open(watcher *Filter) (msg *ReceivedMessage) {
   211  	if watcher == nil {
   212  		return nil
   213  	}
   214  
   215  	// The API interface forbids filters doing both symmetric and asymmetric encryption.
   216  	if watcher.expectsAsymmetricEncryption() && watcher.expectsSymmetricEncryption() {
   217  		return nil
   218  	}
   219  
   220  	if watcher.expectsAsymmetricEncryption() {
   221  		msg, _ = e.OpenAsymmetric(watcher.KeyAsym)
   222  		if msg != nil {
   223  			msg.Dst = &watcher.KeyAsym.PublicKey
   224  		}
   225  	} else if watcher.expectsSymmetricEncryption() {
   226  		msg, _ = e.OpenSymmetric(watcher.KeySym)
   227  		if msg != nil {
   228  			msg.SymKeyHash = crypto.Keccak256Hash(watcher.KeySym)
   229  		}
   230  	}
   231  
   232  	if msg != nil {
   233  		ok := msg.ValidateAndParse()
   234  		if !ok {
   235  			return nil
   236  		}
   237  		msg.Topic = e.Topic
   238  		msg.PoW = e.PoW()
   239  		msg.TTL = e.TTL
   240  		msg.Sent = e.Expiry - e.TTL
   241  		msg.EnvelopeHash = e.Hash()
   242  	}
   243  	return msg
   244  }
   245  
   246  // Bloom maps 4-bytes Topic into 64-byte bloom filter with 3 bits set (at most).
   247  func (e *Envelope) Bloom() []byte {
   248  	if e.bloom == nil {
   249  		e.bloom = TopicToBloom(e.Topic)
   250  	}
   251  	return e.bloom
   252  }
   253  
   254  // TopicToBloom converts the topic (4 bytes) to the bloom filter (64 bytes)
   255  func TopicToBloom(topic TopicType) []byte {
   256  	b := make([]byte, BloomFilterSize)
   257  	var index [3]int
   258  	for j := 0; j < 3; j++ {
   259  		index[j] = int(topic[j])
   260  		if (topic[3] & (1 << uint(j))) != 0 {
   261  			index[j] += 256
   262  		}
   263  	}
   264  
   265  	for j := 0; j < 3; j++ {
   266  		byteIndex := index[j] / 8
   267  		bitIndex := index[j] % 8
   268  		b[byteIndex] = (1 << uint(bitIndex))
   269  	}
   270  	return b
   271  }
   272  
   273  // GetEnvelope retrieves an envelope from the message queue by its hash.
   274  // It returns nil if the envelope can not be found.
   275  func (w *Whisper) GetEnvelope(hash common.Hash) *Envelope {
   276  	w.poolMu.RLock()
   277  	defer w.poolMu.RUnlock()
   278  	return w.envelopes[hash]
   279  }