Skip to content

Commit f7328c5

Browse files
author
Bas van Kervel
committed
rpc: add pub/sub support
1 parent fb578f4 commit f7328c5

16 files changed

Lines changed: 844 additions & 310 deletions

File tree

‎eth/api.go‎

Lines changed: 145 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ import (
2828
"sync"
2929
"time"
3030

31+
"golang.org/x/net/context"
32+
3133
"github.com/ethereum/ethash"
3234
"github.com/ethereum/go-ethereum/accounts"
3335
"github.com/ethereum/go-ethereum/common"
@@ -457,16 +459,46 @@ func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
457459
// It offers only methods that operate on public data that is freely available to anyone.
458460
type PublicBlockChainAPI struct {
459461
config *core.ChainConfig
460-
bc *core.BlockChain
461-
chainDb ethdb.Database
462-
eventMux *event.TypeMux
463-
am *accounts.Manager
464-
miner *miner.Miner
462+
bc *core.BlockChain
463+
chainDb ethdb.Database
464+
eventMux *event.TypeMux
465+
muNewBlockSubscriptions sync.Mutex // protects newBlocksSubscriptions
466+
newBlockSubscriptions map[string]func(core.ChainEvent) error // callbacks for new block subscriptions
467+
am *accounts.Manager
468+
miner *miner.Miner
465469
}
466470

467471
// NewPublicBlockChainAPI creates a new Etheruem blockchain API.
468472
func NewPublicBlockChainAPI(config *core.ChainConfig, bc *core.BlockChain, m *miner.Miner, chainDb ethdb.Database, eventMux *event.TypeMux, am *accounts.Manager) *PublicBlockChainAPI {
469-
return &PublicBlockChainAPI{config: config, bc: bc, miner: m, chainDb: chainDb, eventMux: eventMux, am: am}
473+
api := &PublicBlockChainAPI{
474+
config: config,
475+
bc: bc,
476+
miner: m,
477+
chainDb: chainDb,
478+
eventMux: eventMux,
479+
am: am,
480+
newBlockSubscriptions: make(map[string]func(core.ChainEvent) error),
481+
}
482+
483+
go api.subscriptionLoop()
484+
485+
return api
486+
}
487+
488+
// subscriptionLoop reads events from the global event mux and creates notifications for the matched subscriptions.
489+
func (s *PublicBlockChainAPI) subscriptionLoop() {
490+
sub := s.eventMux.Subscribe(core.ChainEvent{})
491+
for event := range sub.Chan() {
492+
if chainEvent, ok := event.Data.(core.ChainEvent); ok {
493+
s.muNewBlockSubscriptions.Lock()
494+
for id, notifyOf := range s.newBlockSubscriptions {
495+
if notifyOf(chainEvent) == rpc.ErrNotificationNotFound {
496+
delete(s.newBlockSubscriptions, id)
497+
}
498+
}
499+
s.muNewBlockSubscriptions.Unlock()
500+
}
501+
}
470502
}
471503

472504
// BlockNumber returns the block number of the chain head.
@@ -564,20 +596,36 @@ type NewBlocksArgs struct {
564596

565597
// NewBlocks triggers a new block event each time a block is appended to the chain. It accepts an argument which allows
566598
// the caller to specify whether the output should contain transactions and in what format.
567-
func (s *PublicBlockChainAPI) NewBlocks(args NewBlocksArgs) (rpc.Subscription, error) {
568-
sub := s.eventMux.Subscribe(core.ChainEvent{})
599+
func (s *PublicBlockChainAPI) NewBlocks(ctx context.Context, args NewBlocksArgs) (rpc.Subscription, error) {
600+
notifier, supported := ctx.Value(rpc.NotifierContextKey).(rpc.Notifier)
601+
if !supported {
602+
return nil, rpc.ErrNotificationsUnsupported
603+
}
569604

570-
output := func(rawBlock interface{}) interface{} {
571-
if event, ok := rawBlock.(core.ChainEvent); ok {
572-
notification, err := s.rpcOutputBlock(event.Block, args.IncludeTransactions, args.TransactionDetails)
573-
if err == nil {
574-
return notification
575-
}
605+
// create a subscription that will remove itself when unsubscribed/cancelled
606+
subscription, err := notifier.NewSubscription(func(subId string) {
607+
s.muNewBlockSubscriptions.Lock()
608+
delete(s.newBlockSubscriptions, subId)
609+
s.muNewBlockSubscriptions.Unlock()
610+
})
611+
612+
if err != nil {
613+
return nil, err
614+
}
615+
616+
// add a callback that is called on chain events which will format the block and notify the client
617+
s.muNewBlockSubscriptions.Lock()
618+
s.newBlockSubscriptions[subscription.ID()] = func(e core.ChainEvent) error {
619+
if notification, err := s.rpcOutputBlock(e.Block, args.IncludeTransactions, args.TransactionDetails); err == nil {
620+
return subscription.Notify(notification)
621+
} else {
622+
glog.V(logger.Warn).Info("unable to format block %v\n", err)
576623
}
577-
return rawBlock
624+
return nil
578625
}
626+
s.muNewBlockSubscriptions.Unlock()
579627

580-
return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
628+
return subscription, nil
581629
}
582630

583631
// GetCode returns the code stored at the given address in the state for the given block number.
@@ -821,26 +869,75 @@ func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, err
821869

822870
// PublicTransactionPoolAPI exposes methods for the RPC interface
823871
type PublicTransactionPoolAPI struct {
824-
eventMux *event.TypeMux
825-
chainDb ethdb.Database
826-
gpo *GasPriceOracle
827-
bc *core.BlockChain
828-
miner *miner.Miner
829-
am *accounts.Manager
830-
txPool *core.TxPool
831-
txMu sync.Mutex
872+
eventMux *event.TypeMux
873+
chainDb ethdb.Database
874+
gpo *GasPriceOracle
875+
bc *core.BlockChain
876+
miner *miner.Miner
877+
am *accounts.Manager
878+
txPool *core.TxPool
879+
txMu sync.Mutex
880+
muPendingTxSubs sync.Mutex
881+
pendingTxSubs map[string]rpc.Subscription
832882
}
833883

834884
// NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
835885
func NewPublicTransactionPoolAPI(e *Ethereum) *PublicTransactionPoolAPI {
836-
return &PublicTransactionPoolAPI{
837-
eventMux: e.EventMux(),
838-
gpo: NewGasPriceOracle(e),
839-
chainDb: e.ChainDb(),
840-
bc: e.BlockChain(),
841-
am: e.AccountManager(),
842-
txPool: e.TxPool(),
843-
miner: e.Miner(),
886+
api := &PublicTransactionPoolAPI{
887+
eventMux: e.EventMux(),
888+
gpo: NewGasPriceOracle(e),
889+
chainDb: e.ChainDb(),
890+
bc: e.BlockChain(),
891+
am: e.AccountManager(),
892+
txPool: e.TxPool(),
893+
miner: e.Miner(),
894+
pendingTxSubs: make(map[string]rpc.Subscription),
895+
}
896+
897+
go api.subscriptionLoop()
898+
899+
return api
900+
}
901+
902+
// subscriptionLoop listens for events on the global event mux and creates notifications for subscriptions.
903+
func (s *PublicTransactionPoolAPI) subscriptionLoop() {
904+
sub := s.eventMux.Subscribe(core.TxPreEvent{})
905+
accountTimeout := time.NewTicker(10 * time.Second)
906+
907+
// only publish pending tx signed by one of the accounts in the node
908+
accountSet := set.New()
909+
accounts, _ := s.am.Accounts()
910+
for _, acc := range accounts {
911+
accountSet.Add(acc.Address)
912+
}
913+
914+
for {
915+
select {
916+
case event := <-sub.Chan():
917+
if event == nil {
918+
continue
919+
}
920+
tx := event.Data.(core.TxPreEvent)
921+
if from, err := tx.Tx.FromFrontier(); err == nil {
922+
if accountSet.Has(from) {
923+
s.muPendingTxSubs.Lock()
924+
for id, sub := range s.pendingTxSubs {
925+
if sub.Notify(tx.Tx.Hash()) == rpc.ErrNotificationNotFound {
926+
delete(s.pendingTxSubs, id)
927+
}
928+
}
929+
s.muPendingTxSubs.Unlock()
930+
}
931+
}
932+
case <-accountTimeout.C:
933+
// refresh account list when accounts are added/removed from the node.
934+
if accounts, err := s.am.Accounts(); err == nil {
935+
accountSet.Clear()
936+
for _, acc := range accounts {
937+
accountSet.Add(acc.Address)
938+
}
939+
}
940+
}
844941
}
845942
}
846943

@@ -1275,40 +1372,27 @@ func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, err
12751372

12761373
// NewPendingTransaction creates a subscription that is triggered each time a transaction enters the transaction pool
12771374
// and is send from one of the transactions this nodes manages.
1278-
func (s *PublicTransactionPoolAPI) NewPendingTransactions() (rpc.Subscription, error) {
1279-
sub := s.eventMux.Subscribe(core.TxPreEvent{})
1280-
1281-
accounts, err := s.am.Accounts()
1282-
if err != nil {
1283-
return rpc.Subscription{}, err
1375+
func (s *PublicTransactionPoolAPI) NewPendingTransactions(ctx context.Context) (rpc.Subscription, error) {
1376+
notifier, supported := ctx.Value(rpc.NotifierContextKey).(rpc.Notifier)
1377+
if !supported {
1378+
return nil, rpc.ErrNotificationsUnsupported
12841379
}
1285-
accountSet := set.New()
1286-
for _, account := range accounts {
1287-
accountSet.Add(account.Address)
1288-
}
1289-
accountSetLastUpdates := time.Now()
12901380

1291-
output := func(transaction interface{}) interface{} {
1292-
if time.Since(accountSetLastUpdates) > (time.Duration(2) * time.Second) {
1293-
if accounts, err = s.am.Accounts(); err != nil {
1294-
accountSet.Clear()
1295-
for _, account := range accounts {
1296-
accountSet.Add(account.Address)
1297-
}
1298-
accountSetLastUpdates = time.Now()
1299-
}
1300-
}
1381+
subscription, err := notifier.NewSubscription(func(id string) {
1382+
s.muPendingTxSubs.Lock()
1383+
delete(s.pendingTxSubs, id)
1384+
s.muPendingTxSubs.Unlock()
1385+
})
13011386

1302-
tx := transaction.(core.TxPreEvent)
1303-
if from, err := tx.Tx.FromFrontier(); err == nil {
1304-
if accountSet.Has(from) {
1305-
return tx.Tx.Hash()
1306-
}
1307-
}
1308-
return nil
1387+
if err != nil {
1388+
return nil, err
13091389
}
13101390

1311-
return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
1391+
s.muPendingTxSubs.Lock()
1392+
s.pendingTxSubs[subscription.ID()] = subscription
1393+
s.muPendingTxSubs.Unlock()
1394+
1395+
return subscription, nil
13121396
}
13131397

13141398
// Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the

‎eth/backend.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ func (s *Ethereum) APIs() []rpc.API {
310310
}, {
311311
Namespace: "eth",
312312
Version: "1.0",
313-
Service: downloader.NewPublicDownloaderAPI(s.Downloader()),
313+
Service: downloader.NewPublicDownloaderAPI(s.Downloader(), s.EventMux()),
314314
Public: true,
315315
}, {
316316
Namespace: "miner",

‎eth/downloader/api.go‎

Lines changed: 59 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,55 @@
1717
package downloader
1818

1919
import (
20+
"sync"
21+
22+
"golang.org/x/net/context"
23+
24+
"github.com/ethereum/go-ethereum/event"
2025
"github.com/ethereum/go-ethereum/rpc"
2126
)
2227

2328
// PublicDownloaderAPI provides an API which gives information about the current synchronisation status.
2429
// It offers only methods that operates on data that can be available to anyone without security risks.
2530
type PublicDownloaderAPI struct {
26-
d *Downloader
31+
d *Downloader
32+
mux *event.TypeMux
33+
muSyncSubscriptions sync.Mutex
34+
syncSubscriptions map[string]rpc.Subscription
2735
}
2836

2937
// NewPublicDownloaderAPI create a new PublicDownloaderAPI.
30-
func NewPublicDownloaderAPI(d *Downloader) *PublicDownloaderAPI {
31-
return &PublicDownloaderAPI{d}
38+
func NewPublicDownloaderAPI(d *Downloader, m *event.TypeMux) *PublicDownloaderAPI {
39+
api := &PublicDownloaderAPI{d: d, mux: m, syncSubscriptions: make(map[string]rpc.Subscription)}
40+
41+
go api.run()
42+
43+
return api
44+
}
45+
46+
func (api *PublicDownloaderAPI) run() {
47+
sub := api.mux.Subscribe(StartEvent{}, DoneEvent{}, FailedEvent{})
48+
49+
for event := range sub.Chan() {
50+
var notification interface{}
51+
52+
switch event.Data.(type) {
53+
case StartEvent:
54+
result := &SyncingResult{Syncing: true}
55+
result.Status.Origin, result.Status.Current, result.Status.Height, result.Status.Pulled, result.Status.Known = api.d.Progress()
56+
notification = result
57+
case DoneEvent, FailedEvent:
58+
notification = false
59+
}
60+
61+
api.muSyncSubscriptions.Lock()
62+
for id, sub := range api.syncSubscriptions {
63+
if sub.Notify(notification) == rpc.ErrNotificationNotFound {
64+
delete(api.syncSubscriptions, id)
65+
}
66+
}
67+
api.muSyncSubscriptions.Unlock()
68+
}
3269
}
3370

3471
// Progress gives progress indications when the node is synchronising with the Ethereum network.
@@ -47,19 +84,25 @@ type SyncingResult struct {
4784
}
4885

4986
// Syncing provides information when this nodes starts synchronising with the Ethereum network and when it's finished.
50-
func (s *PublicDownloaderAPI) Syncing() (rpc.Subscription, error) {
51-
sub := s.d.mux.Subscribe(StartEvent{}, DoneEvent{}, FailedEvent{})
87+
func (api *PublicDownloaderAPI) Syncing(ctx context.Context) (rpc.Subscription, error) {
88+
notifier, supported := ctx.Value(rpc.NotifierContextKey).(rpc.Notifier)
89+
if !supported {
90+
return nil, rpc.ErrNotificationsUnsupported
91+
}
5292

53-
output := func(event interface{}) interface{} {
54-
switch event.(type) {
55-
case StartEvent:
56-
result := &SyncingResult{Syncing: true}
57-
result.Status.Origin, result.Status.Current, result.Status.Height, result.Status.Pulled, result.Status.Known = s.d.Progress()
58-
return result
59-
case DoneEvent, FailedEvent:
60-
return false
61-
}
62-
return nil
93+
subscription, err := notifier.NewSubscription(func(id string) {
94+
api.muSyncSubscriptions.Lock()
95+
delete(api.syncSubscriptions, id)
96+
api.muSyncSubscriptions.Unlock()
97+
})
98+
99+
if err != nil {
100+
return nil, err
63101
}
64-
return rpc.NewSubscriptionWithOutputFormat(sub, output), nil
102+
103+
api.muSyncSubscriptions.Lock()
104+
api.syncSubscriptions[subscription.ID()] = subscription
105+
api.muSyncSubscriptions.Unlock()
106+
107+
return subscription, nil
65108
}

0 commit comments

Comments
 (0)