swarm/swap: p2p protocol implementation

This commit is contained in:
Fabio Barone 2018-10-03 17:07:53 -05:00
parent 3d234cdbbb
commit 1ef101b18b
3 changed files with 11 additions and 31 deletions

View file

@ -141,11 +141,22 @@ type Spec struct {
// each message must have a single unique data type
Messages []interface{}
Services map[string]ProtocolService
initOnce sync.Once
codes map[reflect.Type]uint64
types map[uint64]reflect.Type
}
type ProtocolService interface {
AddServiceData(data interface{})
IsSupported(key interface{})
}
func (s *Spec) RegisterProtocolService(key string, service ProtocolService) {
s.Services[key] = service
}
func (s *Spec) init() {
s.initOnce.Do(func() {
s.codes = make(map[reflect.Type]uint64, len(s.Messages))

View file

@ -81,7 +81,6 @@ type RedeemChequeMsg struct {
// SECTION: node.Service interface
/////////////////////////////////////////////////////////////////////
func (s *Swap) Start(srv *p2p.Server) error {
s.registerForEvents(srv)
log.Debug("Started swap")
return nil
}

View file

@ -163,36 +163,6 @@ func (dpo *DefaultPriceOracle) GetPriceForMsg(event *p2p.PeerEvent) (*big.Int, E
return nil, false
}
//This swap implementation works by listening to message events on the p2p server.
//It then handles the event received, filtering for messages and evaluating
//if it needs accounting
func (s *Swap) registerForEvents(srv *p2p.Server) {
go func() {
events := make(chan *p2p.PeerEvent)
sub := srv.SubscribeEvents(events)
defer sub.Unsubscribe()
for {
select {
case event := <-events:
go s.handleMsgEvent(event)
case err := <-sub.Err():
log.Error(err.Error())
return
}
}
}()
}
//Handle the message.
//Determine if it needs accounting, and if yes, account for it
func (s *Swap) handleMsgEvent(event *p2p.PeerEvent) {
if !s.priceOracle.IsAccountedMsg(event) {
return
}
s.accountMsgForPeer(event)
}
//Do the accounting
//Depending on the charging type of the message (set in the PriceTag),
//it will charge the sender or receiver