2014-12-08 03:43:33 -08:00
|
|
|
package whisper
|
|
|
|
|
2014-12-09 15:03:50 -08:00
|
|
|
import (
|
2014-12-10 05:17:32 -08:00
|
|
|
"crypto/ecdsa"
|
2014-12-09 15:03:50 -08:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
|
|
)
|
|
|
|
|
2014-12-08 03:43:33 -08:00
|
|
|
type Message struct {
|
|
|
|
Flags byte
|
|
|
|
Signature []byte
|
|
|
|
Payload []byte
|
2015-02-03 06:56:19 -08:00
|
|
|
Sent uint64
|
2014-12-08 03:43:33 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewMessage(payload []byte) *Message {
|
|
|
|
return &Message{Flags: 0, Payload: payload}
|
|
|
|
}
|
|
|
|
|
2014-12-09 15:03:50 -08:00
|
|
|
func (self *Message) hash() []byte {
|
|
|
|
return crypto.Sha3(append([]byte{self.Flags}, self.Payload...))
|
|
|
|
}
|
|
|
|
|
2014-12-10 05:17:32 -08:00
|
|
|
func (self *Message) sign(key *ecdsa.PrivateKey) (err error) {
|
2014-12-09 15:03:50 -08:00
|
|
|
self.Flags = 1
|
|
|
|
self.Signature, err = crypto.Sign(self.hash(), key)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-12-10 05:17:32 -08:00
|
|
|
func (self *Message) Recover() *ecdsa.PublicKey {
|
2014-12-12 13:23:42 -08:00
|
|
|
defer func() { recover() }() // in case of invalid sig
|
2014-12-10 05:17:32 -08:00
|
|
|
return crypto.SigToPub(self.hash(), self.Signature)
|
|
|
|
}
|
|
|
|
|
2014-12-12 13:23:42 -08:00
|
|
|
func (self *Message) Encrypt(to *ecdsa.PublicKey) (err error) {
|
2014-12-09 15:03:50 -08:00
|
|
|
self.Payload, err = crypto.Encrypt(to, self.Payload)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-12-08 03:43:33 -08:00
|
|
|
func (self *Message) Bytes() []byte {
|
|
|
|
return append([]byte{self.Flags}, append(self.Signature, self.Payload...)...)
|
|
|
|
}
|
2014-12-09 15:03:50 -08:00
|
|
|
|
|
|
|
type Opts struct {
|
2014-12-10 05:17:32 -08:00
|
|
|
From *ecdsa.PrivateKey
|
|
|
|
To *ecdsa.PublicKey
|
|
|
|
Ttl time.Duration
|
|
|
|
Topics [][]byte
|
2014-12-09 15:03:50 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (self *Message) Seal(pow time.Duration, opts Opts) (*Envelope, error) {
|
2014-12-12 13:23:42 -08:00
|
|
|
if opts.From != nil {
|
|
|
|
err := self.sign(opts.From)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if opts.To != nil {
|
|
|
|
err := self.Encrypt(opts.To)
|
|
|
|
if err != nil {
|
2014-12-09 15:03:50 -08:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-13 04:36:44 -08:00
|
|
|
if opts.Ttl == 0 {
|
|
|
|
opts.Ttl = DefaultTtl
|
|
|
|
}
|
|
|
|
|
|
|
|
envelope := NewEnvelope(opts.Ttl, opts.Topics, self)
|
2014-12-09 15:03:50 -08:00
|
|
|
envelope.Seal(pow)
|
|
|
|
|
|
|
|
return envelope, nil
|
|
|
|
}
|