@@ -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.
458460type 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.
468472func 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
823871type 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.
835885func 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
0 commit comments