aboutsummaryrefslogtreecommitdiffstats
path: root/whisper/envelope.go
blob: 65dc89936203367234d765485b727ecebe7bf50e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package whisper

import (
    "crypto/ecdsa"
    "encoding/binary"
    "fmt"
    "time"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/crypto/ecies"
    "github.com/ethereum/go-ethereum/rlp"
)

const (
    DefaultPow = 50 * time.Millisecond
)

type Envelope struct {
    Expiry uint32 // Whisper protocol specifies int32, really should be int64
    TTL    uint32 // ^^^^^^
    Topics [][]byte
    Data   []byte
    Nonce  uint32

    hash common.Hash
}

func (self *Envelope) Hash() common.Hash {
    if (self.hash == common.Hash{}) {
        enc, _ := rlp.EncodeToBytes(self)
        self.hash = crypto.Sha3Hash(enc)
    }
    return self.hash
}

func NewEnvelope(ttl time.Duration, topics [][]byte, data *Message) *Envelope {
    exp := time.Now().Add(ttl)
    return &Envelope{
        Expiry: uint32(exp.Unix()),
        TTL:    uint32(ttl.Seconds()),
        Topics: topics,
        Data:   data.bytes(),
        Nonce:  0,
    }
}

func (self *Envelope) Seal(pow time.Duration) {
    self.proveWork(pow)
}

func (self *Envelope) Open(key *ecdsa.PrivateKey) (msg *Message, err error) {
    data := self.Data

    message := Message{
        Flags: data[0],
    }
    data = data[1:]

    if message.Flags&128 == 128 {
        if len(data) < 65 {
            return nil, fmt.Errorf("unable to open envelope. First bit set but len(data) < 65")
        }
        message.Signature, data = data[:65], data[65:]
    }
    message.Payload = data

    if key != nil {
        message.Payload, err = crypto.Decrypt(key, message.Payload)
        switch err {
        case nil: // OK
        case ecies.ErrInvalidPublicKey: // Payload isn't encrypted
            return &message, err
        default:
            return nil, fmt.Errorf("unable to open envelope. Decrypt failed: %v", err)
        }
    }
    return &message, nil
}

func (self *Envelope) proveWork(dura time.Duration) {
    var bestBit int
    d := make([]byte, 64)
    enc, _ := rlp.EncodeToBytes(self.withoutNonce())
    copy(d[:32], enc)

    then := time.Now().Add(dura).UnixNano()
    for n := uint32(0); time.Now().UnixNano() < then; {
        for i := 0; i < 1024; i++ {
            binary.BigEndian.PutUint32(d[60:], n)

            fbs := common.FirstBitSet(common.BigD(crypto.Sha3(d)))
            if fbs > bestBit {
                bestBit = fbs
                self.Nonce = n
            }

            n++
        }
    }
}

func (self *Envelope) valid() bool {
    d := make([]byte, 64)
    enc, _ := rlp.EncodeToBytes(self.withoutNonce())
    copy(d[:32], enc)
    binary.BigEndian.PutUint32(d[60:], self.Nonce)
    return common.FirstBitSet(common.BigD(crypto.Sha3(d))) > 0
}

func (self *Envelope) withoutNonce() interface{} {
    return []interface{}{self.Expiry, self.TTL, self.Topics, self.Data}
}

// rlpenv is an Envelope but is not an rlp.Decoder.
// It is used for decoding because we need to
type rlpenv Envelope

func (self *Envelope) DecodeRLP(s *rlp.Stream) error {
    raw, err := s.Raw()
    if err != nil {
        return err
    }
    if err := rlp.DecodeBytes(raw, (*rlpenv)(self)); err != nil {
        return err
    }
    self.hash = crypto.Sha3Hash(raw)
    return nil
}