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