aboutsummaryrefslogtreecommitdiffstats
path: root/whisper/mailserver/mailserver.go
blob: d705c622f4ceeda20d8dea248606631538a0dc0f (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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright 2016 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

package mailserver

import (
    "bytes"
    "encoding/binary"
    "fmt"

    "github.com/ethereum/go-ethereum/cmd/utils"
    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/log"
    "github.com/ethereum/go-ethereum/rlp"
    whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
    "github.com/syndtr/goleveldb/leveldb"
    "github.com/syndtr/goleveldb/leveldb/util"
)

type WMailServer struct {
    db  *leveldb.DB
    w   *whisper.Whisper
    pow float64
    key []byte
}

type DBKey struct {
    timestamp uint32
    hash      common.Hash
    raw       []byte
}

func NewDbKey(t uint32, h common.Hash) *DBKey {
    const sz = common.HashLength + 4
    var k DBKey
    k.timestamp = t
    k.hash = h
    k.raw = make([]byte, sz)
    binary.BigEndian.PutUint32(k.raw, k.timestamp)
    copy(k.raw[4:], k.hash[:])
    return &k
}

func (s *WMailServer) Init(shh *whisper.Whisper, path string, password string, pow float64) {
    var err error
    if len(path) == 0 {
        utils.Fatalf("DB file is not specified")
    }

    if len(password) == 0 {
        utils.Fatalf("Password is not specified for MailServer")
    }

    s.db, err = leveldb.OpenFile(path, nil)
    if err != nil {
        utils.Fatalf("Failed to open DB file: %s", err)
    }

    s.w = shh
    s.pow = pow

    MailServerKeyID, err := s.w.AddSymKeyFromPassword(password)
    if err != nil {
        utils.Fatalf("Failed to create symmetric key for MailServer: %s", err)
    }
    s.key, err = s.w.GetSymKey(MailServerKeyID)
    if err != nil {
        utils.Fatalf("Failed to save symmetric key for MailServer")
    }
}

func (s *WMailServer) Close() {
    if s.db != nil {
        s.db.Close()
    }
}

func (s *WMailServer) Archive(env *whisper.Envelope) {
    key := NewDbKey(env.Expiry-env.TTL, env.Hash())
    rawEnvelope, err := rlp.EncodeToBytes(env)
    if err != nil {
        log.Error(fmt.Sprintf("rlp.EncodeToBytes failed: %s", err))
    } else {
        err = s.db.Put(key.raw, rawEnvelope, nil)
        if err != nil {
            log.Error(fmt.Sprintf("Writing to DB failed: %s", err))
        }
    }
}

func (s *WMailServer) DeliverMail(peer *whisper.Peer, request *whisper.Envelope) {
    if peer == nil {
        log.Error(fmt.Sprint("Whisper peer is nil"))
        return
    }

    ok, lower, upper, topic := s.validateRequest(peer.ID(), request)
    if ok {
        s.processRequest(peer, lower, upper, topic)
    }
}

func (s *WMailServer) processRequest(peer *whisper.Peer, lower, upper uint32, topic whisper.TopicType) []*whisper.Envelope {
    ret := make([]*whisper.Envelope, 0)
    var err error
    var zero common.Hash
    var empty whisper.TopicType
    kl := NewDbKey(lower, zero)
    ku := NewDbKey(upper, zero)
    i := s.db.NewIterator(&util.Range{Start: kl.raw, Limit: ku.raw}, nil)
    defer i.Release()

    for i.Next() {
        var envelope whisper.Envelope
        err = rlp.DecodeBytes(i.Value(), &envelope)
        if err != nil {
            log.Error(fmt.Sprintf("RLP decoding failed: %s", err))
        }

        if topic == empty || envelope.Topic == topic {
            if peer == nil {
                // used for test purposes
                ret = append(ret, &envelope)
            } else {
                err = s.w.SendP2PDirect(peer, &envelope)
                if err != nil {
                    log.Error(fmt.Sprintf("Failed to send direct message to peer: %s", err))
                    return nil
                }
            }
        }
    }

    err = i.Error()
    if err != nil {
        log.Error(fmt.Sprintf("Level DB iterator error: %s", err))
    }

    return ret
}

func (s *WMailServer) validateRequest(peerID []byte, request *whisper.Envelope) (bool, uint32, uint32, whisper.TopicType) {
    var topic whisper.TopicType
    if s.pow > 0.0 && request.PoW() < s.pow {
        return false, 0, 0, topic
    }

    f := whisper.Filter{KeySym: s.key}
    decrypted := request.Open(&f)
    if decrypted == nil {
        log.Warn(fmt.Sprintf("Failed to decrypt p2p request"))
        return false, 0, 0, topic
    }

    if len(decrypted.Payload) < 8 {
        log.Warn(fmt.Sprintf("Undersized p2p request"))
        return false, 0, 0, topic
    }

    src := crypto.FromECDSAPub(decrypted.Src)
    if len(src)-len(peerID) == 1 {
        src = src[1:]
    }
    if !bytes.Equal(peerID, src) {
        log.Warn(fmt.Sprintf("Wrong signature of p2p request"))
        return false, 0, 0, topic
    }

    lower := binary.BigEndian.Uint32(decrypted.Payload[:4])
    upper := binary.BigEndian.Uint32(decrypted.Payload[4:8])

    if len(decrypted.Payload) >= 8+whisper.TopicLength {
        topic = whisper.BytesToTopic(decrypted.Payload[8:])
    }

    return true, lower, upper, topic
}