2014-12-08 05:43:33 -06:00
|
|
|
package whisper
|
|
|
|
|
2014-12-09 17:03:50 -06:00
|
|
|
import (
|
2014-12-10 07:17:32 -06:00
|
|
|
"crypto/ecdsa"
|
2014-12-09 17:03:50 -06:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
|
|
)
|
|
|
|
|
2014-12-08 05:43:33 -06:00
|
|
|
type Message struct {
|
|
|
|
Flags byte
|
|
|
|
Signature []byte
|
|
|
|
Payload []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMessage(payload []byte) *Message {
|
|
|
|
return &Message{Flags: 0, Payload: payload}
|
|
|
|
}
|
|
|
|
|
2014-12-09 17:03:50 -06:00
|
|
|
func (self *Message) hash() []byte {
|
|
|
|
return crypto.Sha3(append([]byte{self.Flags}, self.Payload...))
|
|
|
|
}
|
|
|
|
|
2014-12-10 07:17:32 -06:00
|
|
|
func (self *Message) sign(key *ecdsa.PrivateKey) (err error) {
|
2014-12-09 17:03:50 -06:00
|
|
|
self.Flags = 1
|
|
|
|
self.Signature, err = crypto.Sign(self.hash(), key)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-12-10 07:17:32 -06:00
|
|
|
func (self *Message) Recover() *ecdsa.PublicKey {
|
|
|
|
return crypto.SigToPub(self.hash(), self.Signature)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (self *Message) Encrypt(from *ecdsa.PrivateKey, to *ecdsa.PublicKey) (err error) {
|
2014-12-09 17:03:50 -06:00
|
|
|
err = self.sign(from)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
self.Payload, err = crypto.Encrypt(to, self.Payload)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2014-12-08 05:43:33 -06:00
|
|
|
func (self *Message) Bytes() []byte {
|
|
|
|
return append([]byte{self.Flags}, append(self.Signature, self.Payload...)...)
|
|
|
|
}
|
2014-12-09 17:03:50 -06:00
|
|
|
|
|
|
|
type Opts struct {
|
2014-12-10 07:17:32 -06:00
|
|
|
From *ecdsa.PrivateKey
|
|
|
|
To *ecdsa.PublicKey
|
|
|
|
Ttl time.Duration
|
|
|
|
Topics [][]byte
|
2014-12-09 17:03:50 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func (self *Message) Seal(pow time.Duration, opts Opts) (*Envelope, error) {
|
2014-12-10 07:17:32 -06:00
|
|
|
if opts.To != nil && opts.From != nil {
|
2014-12-09 17:03:50 -06:00
|
|
|
if err := self.Encrypt(opts.From, opts.To); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
envelope := NewEnvelope(DefaultTtl, opts.Topics, self)
|
|
|
|
envelope.Seal(pow)
|
|
|
|
|
|
|
|
return envelope, nil
|
|
|
|
}
|