Repository navigation
protocol 1.6: minimal update to get broadcast_package out - #6
Conversation
This is a minimal changeset for a new protocol version. The ideas for the less trivial changes are deferred a bit, just so we get something out. ref spesmilo#2 ref spesmilo/electrumx#90
|
@romanz, @cculianu, @ecdsa, @craigraw, @tnull The changes are small, we will probably have a branch for electrumx by tomorrow. EDIT2: implementation in Electrum client: spesmilo/electrum#10295 |
|
Concept ACK 7b84d2a, thanks! |
|
ACK, this is a useful update, and I think it makes sense to make incremental changes. I'll save my requests for the next version :) |
Looks very reasonable! regarding the concatenation -> list for headers — what is the rationale for this? my biggest concern here is I really hate apis that return different results based on versioning — although I know that is the philosophy behind the electrum protocol — it just makes me uneasy that some wallet dev or some api out there will have extra burden created by a breaking api I would prefer adding a new method name that returns list or having it take an optional extra arg to indicate list Rationale again is I fear negative value is created for the world every time some devs (in this case us) introduce api breakage and in this case it’s not like there’s that much burden on us to continue to send it as a concatenation… literally in python joining a string from a list is implemented on the C side anyway so.. Yes in hindsight it would have been more aesthetic had the headers response been a list… for sure. but again I feel more burden is exacted on the world now to change it.. my two cents. edit: also note it’s faster in general in most json libs to parse 1 giant string that is N 80-byte headers concatenated than it is to parse a list of N items, each being a string of 80 bytes .. so there’s that.. but that is minor |
| * *headers* | ||
|
|
||
| The binary block headers concatenated together in-order as a | ||
| hexadecimal string. Starting with version 1.4.1, AuxPoW data (if present | ||
| in the original header) is truncated if *cp_height* is nonzero. | ||
| An array containing the binary block headers in-order; each header is a | ||
| hexadecimal string. AuxPoW data (if present in the original header) is | ||
| truncated if *cp_height* is nonzero. |
There was a problem hiding this comment.
Looks very reasonable!
regarding the concatenation -> list for headers — what is the rationale for this?
my biggest concern here is I really hate apis that return different results based on versioning — although I know that is the philosophy behind the electrum protocol — it just makes me uneasy that some wallet dev or some api out there will have extra burden created by a breaking api
I would prefer adding a new method name that returns list or having it take an optional extra arg to indicate list
Rationale again is I fear negative value is created for the world every time some devs (in this case us) introduce api breakage and in this case it’s not like there’s that much burden on us to continue to send it as a concatenation… literally in python joining a string from a list is implemented on the C side anyway so..
Yes in hindsight it would have been more aesthetic had the headers response been a list… for sure.
but again I feel more burden is exacted on the world now to change it.. my two cents.
edit: also note it’s faster in general in most json libs to parse 1 giant string that is N 80-byte headers concatenated than it is to parse a list of N items, each being a string of 80 bytes .. so there’s that.. but that is minor
regarding the concatenation -> list for headers — what is the rationale for this?
That change was originally asked for Namecoin as it has variable sized headers.
For any of our use cases, there is no practical gain at all. In fact it makes the response size around 2% larger :P
Nevertheless, it is a conceptual clean-up, and even if we don't care about altcoins I think it's nice to do this small cheap generalisation here.
The earliest non-IRC discussion about it is probably:
spesmilo/electrumx#109
I also think putting this small breaking change into the API serves as a sanity-check whether an implementation that bumps the version number really read and implemented the spec :)
One of the main points of having a version number and negotiation is to allow making breaking changes.
I would prefer [...] having it take an optional extra arg to indicate list
I don't want the API to offer a choice between concatted str and a list. Would rather keep the API simple.
I would prefer adding a new method name that returns list
Sure, if you think that's better, we could rename the method to make the breaking change obvious. (i.e. rm the old method and add a new method with a different name)
But then I would remove the current method (so just do a rename). I already gave this some thought in the context of blockchain.relayfee vs mempool.get_info, where we could e.g. mark blockchain.relayfee as deprecated and then only rm it in a later version, but as there is a direct replacement API, I think there is no point and we should just rm it right away. Same thinking here if we rename it.
Ultimately it's the least interesting change, so if controversial, we could also drop it.
There was a problem hiding this comment.
variable sized headers.
Ahh. Well that settles it, then. Yes, if the protocol is to support such coins, one needs this.
bumps the version number really read and implemented the spec :)
Ha ha.
Sure, if you think that's better, we could rename the method to make the breaking change obvious. (i.e. rm the old method and add a new method with a different name)
No, it's fine. Since you prefer simplicity (as do I), it's ok. Yes, that is a good point about namecoin needing this and a good point as well about the entire point of version negotiation. I think it's fine as proposed, then.
As for mempool.relayfee vs mempool.get_info.. I also think as proposed it's fine. No need to change anything. Stick to the proposal you have so you can get this out the door faster.
There was a problem hiding this comment.
(it's nicer to keep discussions threaded)
That change was originally asked for Namecoin as it has variable sized headers.
Making a change to
blockchain.block.headersis unnecessary for this (niche) use case - Namecoin can already use JSON-RPC batching withblockchain.block.headerto retrieve a bunch of variable sized headers. Given this, consider whether making this breaking change actually does more harm than good?
Using JSON-RPC batching to fetch n single headers compared to a single RPC to fetch a list/concat increases the upstream bandwidth to around n times as large (and the downstream to around 20% more - less if the headers are much larger than 2*80 bytes). (Then as n reaches the chunk size, e.g. 2016, the factor stops growing. Requesting 10**6 headers only increases the upstream bw to 2016x)
It is also higher CPU load on the server to process 2016 RPCs vs just 1.
So yes, indeed requesting headers one-by-one is a workaround. Though there is a reason this separate RPC for requesting a chunk of headers exists in the first place - it is purely for efficiency.
EDIT: I can demonstrate why it creates more work for wallet devs even if they implement version negotiation correctly.
Any change in the protocol creates some work for client/server devs, even more so if they want to support multiple protocol versions at the same time.
There was a problem hiding this comment.
Any change in the protocol creates some work for client/server devs, even more so if they want to support multiple protocol versions at the same time.
Fair enough. However I'd like to say that when one "breaks" an existing API, in order to avoid annoying people, it's nice to also "reward" the dev who now has extra work to do.. with some new feature or facility on account of the fact that he was asked to do some extra work. This is how one makes people happy, and keeps them from being resentful.
In this case: an API nobody ever worries about (headers), now needs to be worried-about, with 0 or almost no benefit for 99.9% of code out there. Would have been less antagonistic to users of this protocol to just offer up a blockchain.block.headers2 or somesuch for the headers-as-list people. Just sayin'.
Anyway yeah I'm fine with moving ahead and not belaboring this point any further... let's get 1.6 out the door.
|
looks good, a4f158c |
Making a change to |
I'm glad you're also conservative on this as am I. I am willing to go either way on it but I do think FWIW that it will be annoying to devs to have to worry about this incongruity in the API; if it were 100% up to me I would have just created a second method with a different name that does almost the same thing, but returns results in an alternate format (headers-as-list). Why? Because on top of the incongruity argument, even on v 1.6 it would save an inconsequential number of bytes (~4%) on the server and client-side when serializing/sending/receiving/parsing the JSON. So there is a slight slight slight perhaps immaterial but nonzero advantage to status quo for non-variable-sized-header chains. FWIW, though, I'm also OK with the explanation given and given that this protocol does support version negotiation, that's what that facility is for. And, on some level, returning a big blob of headers feels "ugly" and returning them as a list is more "aesthetically pleasing". So yeah, I'm ok with either way but I do appreciate the sentiment we share that breaking changes are sorta uncomfortable... EDIT: I can demonstrate why it creates more work for wallet devs even if they implement version negotiation correctly. Say you are a wallet that would like to make use of the new 1.6 API, (perhaps My two cents. The reason why I argue for this so fervently is i am exhausted with e.g. Apple for example breaking old APIs and creating busy work for devs. Sometimes it feels like I'm swimming in slippery pasta when I program natively for iOS and/or macOS and I dare to bump up the SDK version... So I'm like.. kinda traumatized by APIs that do that -- create extra new work for you just to get back to what was working before. That being said, I'm ok with just pushing forward as is proposed. Would be nice to just have the new version out, regardless -- just in future breaking old ancient stuff that was working just fine is kind of just creating busy work for devs so.. /end rant |
|
|
||
| .. note:: The exact relay behaviour might depend on the bitcoind version of the server. | ||
|
|
||
| .. note:: Server implementations should verify (e.g. by enforcing a minimum bitcoind version at runtime) |
There was a problem hiding this comment.
Umm.. should we be adding this to the server.features map as a keyword? Maybe submitpackage? This way wallet clients know right away if the RPC exists? Or are we just going to specify they can expect errors from this RPC if the underlying bitcoind submitpackage RPC is missing and be ok with that? Or are we going to specify that all "1.6 compliant" implementations for BTC must be running on Core >= 28.0.0?
There was a problem hiding this comment.
In theory the backing bitcoind could also be btcd, etc. It would be nice not to "require" Bitcoin Core in the protocol itself.
Specific server implementations can require Bitcoin Core or specific versions of Core, that's fine I think, but the protocol ideally should not. Maybe btcd has an equivalent RPC to submitpackage and a server implementation is then free to use that.
The expectation is that if the server claims to support protocol version 1.6, they should have a working blockchain.transaction.broadcast_package. Hence I see no point in putting stuff into server.features for this.
There was a problem hiding this comment.
The expectation is that if the server claims to support protocol version 1.6, they should have a working blockchain.transaction.broadcast_package. Hence I see no point in putting stuff into server.features for this.
EDIT: Oh, I see, @SomberNight said he is opposed to claiming 1.6 if this facility is missing.
Well, fine. I'm adding the key anyway. I will support "1.6" on Fulcrum with or without
submitpackagebeing present. Fulcrum runs multi-coin anyway so requiring something that doesn't even exist on other coins as a facility for a new protocol version seems crazy to me.. but you guys do what you like. I'll continue to maintain my "almost 100% compatible" specification, which will be more loose/liberal than yours, I guess, and will denote features supported via features flags...
electrumx requires Bitcoin Core 28.0+ if COIN=Bitcoin is set. Couldn't you just special-case BTC similarly: require a working submitpackage only in that case? Obviously for the other coins do whatever you feel like.
There was a problem hiding this comment.
How does everybody here feel about adding a key to the
server.featuresmap to indicate thatblockchain.transaction.broadcast_packageis supported?
If you have logic to determine whether broadcast_package is supported, even for non-Core bitcoinds (e.g. btcd), I think it would be better to hard crash and tell the server operator to upgrade their bitcoind.
What exactly is the scenario you are trying to support?
- is it for "BTC", using old "Bitcoin Core"? in that case the server should either not advertise 1.6 -- or just crash and tell the operator to upgrade bitcoind
- is it for "BTC", using "btcd"/etc? in that case you/we should research if btcd has an equivalent RPC, figure out how to test for the presence of that, and behave similarly as in the "Bitcoin Core" case
- is it for other coins with daemons that do not have submitpackage or care about the package-relay concept at all? sure the RPC does not make sense there and feel free to leave it non-functional or whatever
Is it that in the case of (1), you don't want to force the operator to upgrade their bitcoind? Why? If they upgraded the electrum server, why can they not be expected to also upgrade bitcoind around the same time?
There was a problem hiding this comment.
you don't want to force the operator to upgrade their bitcoind? Why?
Does this even need a reply? If the answer to this question is not self evident to you — nothing I can say here will help.
but let me try:
it appears you are some sort of centralist or statist in philosophy, if I may be frank. That’s fine about 60% of the population has this mentality so it’s normal.
but that’s besides the point:
the role of this software is not to dictate terms to people but rather to help people do what they want to do, within reason.
also the entire point of the soft fork philosophy bitcoin core is in is precisely because they don’t want to “force” upgrades on nodes.
given that Bitcoin BTC is this way — it is doubly silly to force people to upgrade to latest core, when BTC already is paying a considerable cost in terms of technical debt to always soft fork and never hard fork.
Given that BTC has already paid this cost in order to benefit people from not being required to upgrade — it’s silly to then turn around and have the philosophy to force upgrades.
sorry, I’m not gunna play this game of dictating policy on people. I’m a libertarian and a voluntaryist. I try to offer people choice and not shove things down their throats by leveraging influence due to popularity of my software …
but you do you — like I said this is open source we are free to voluntarily participate or not.
There was a problem hiding this comment.
just crash
Are you serious?
Yes. I meant gracefully exit with a human-readable error message, rather than e.g. a segfault. I hope that was obvious.
you don't want to force the operator to upgrade their bitcoind? Why?
Does this even need a reply? If the answer to this question is not self evident to you — nothing I can say here will help.
Do you also support bitcoin core 0.3 then? Where do you draw the line? It is actively harmful to run a public server that auto-connect clients might connect to if it's backed by an ancient bitcoind. Old bitcoinds often have very strict relay policies. For example, the user would not be able to broadcast a tx paying to a taproot address. That is actively harmful. Do you want to expose that in server.features too? Whether the client is allowed to pay to a taproot address?
(EDIT: to be clear, paying to a taproot address is just one example, I can come up with several more if needed. For example, paying to a segwit v0 address was added in 0.13, then paying from was added in 0.13.1, then there was the CPFP carveout which is needed for lightning, then there was spending from a taproot address (added later than paying to), then there are recent datacarrier size changes, there is pay-to-anchor, v3 transactions, etc. Do you want to make all this optional and signal it one-by-one?)
EDIT2: Most of the standardness/relay changes are either already needed by Lightning or will be relied on in the future. A client wanting to use LN expects them to be supported by servers.
There was a problem hiding this comment.
Your philosophy is refuse to claim support for 1.6 if submitpackages is missing — with no consideration for other coins or networks where the entire facility is absent as a concept. You also recommend hard exit on lack of this RPC rather than warning and features map stuff. You also seem to be deeply shocked that I wouldn't be on-board with "forcing" people to do things.
I suspect this is from a lack of ability to deal with heterogeneity. A need for homogeneity -- to wrangle chaos into simplicity... at the expense of consideration for others?
Or.. Not sure if you’re being careless, or are on a power trip… or what.
The language you use “crash the node” and “force upgrade” is reckless and betrays a lack of respect for other people.
Maybe English isn’t your first language and maybe in German such concepts are not offensive but to me your linguistic choices in how you express yourself are distasteful. They reveal a sense of importance that is bordering on abusive behavior… which is a trap software authors fall into.
I am trying to warn you that this is bad design. It's far better to make use of the features map esp. since the rate of adoption of >= v28 Core/Knots is low. You don't want to antagonize your admins. It's better to warn on startup like I do here: cculianu/Fulcrum@06b50dc#diff-3884123fb22804742dac29791cafa44d2305af37f752aada08460afff7d5c4dcR319-R320
Let me say this: This is 1 relatively new method that may not even exist on other coins.
Nodes capable of even offering this method make up maybe 20% of the BTC network at the present time.
Yet your solution is to insist that you cannot be 1.6 or above as an electrum server if this method is missing
This is a method that is only on a few coins (BTC, Namecoin, and some others)
Last I checked this is a multi coin protocol.
You are literally requiring a feature that only exists on 2-3 coins out of N as a requirement for this protocol going forward.. from now until the end of time. Nodes or even entire coins lacking submitpackages are forever relegated to 1.4 or 1.5 protocol version for all eternity — is what you are proposing.
Can you not take a look at yourself honestly here ?
And all for submitpackages which is experimental as per the rpc docs
Comparing it to segwit or taproot or v0.0.3 other stuff is not honest argumentation on your part (you are intentionally not arguing in good faith here. Stop being manipulative and be reasonable!). Also during a transition period where new features are introduced -- is why you have a features map in the first place! Also -- wallets that care about submitpackage need to check the features map anyway for protocol version.. so it's not like even an extra thing is needed to determine yes/no on that feature. But more to the point: You don't "force" people to do stuff. You nag them and you offer gentle reminders. And you offer a transition period upgrade path. "Forcing" people to do things is a nice way to "lose" people.
You don’t see a problem with that?
Also about core v28.0.0 in particular -- it bumped up the glibc version so if you are on like Ubuntu 20 or below I don't think it will even run unless you recompile it (but then you need to figure out how to get a new enough C++ compiler for it on an older system). It's not like forcing people to go to v28.0.0 doesn't have any conceivable headaches associated with it.. it may, for some admins, in some circumstances.
Also you are refusing to allow the specification to make room for cases where this feature is absent (such as in other coins) — it’s not even considered as a possibility in your world-view or in your specification!
I’m sorry I refuse to participate .. you are either intentionally obtuse or on some power trip.
I’ll just adopt 1.6 in a more flexible fashion than the draconian thing you have proposed.
open source after all…
thanks for the chat
EDIT: If you account for Knots (which also has this method) it's more like 39%-49% or thereabouts (not sure how those Knots numbers map to version numbers tbqh). Still not a majority feature. Just sayin'. "Forcing" is .. not cool. server.features exists... use it!
There was a problem hiding this comment.
To get facts out first, around 70% of the Bitcoin network runs Core 28+ or Knots 28+ . (see https://luke.dashjr.org/programs/bitcoin/files/charts/branches.html).
Also note that electrum server operators typically upgrade faster than the average node operator. Also note that I am suggesting tying the upgrading of the electrum server itself to the upgrading of the bitcoind, in this case. Many people running old bitcoinds are unlikely to run a new electrum server.
But this is not even the main point. The main point is that I was only suggesting this for BTC, not for altcoins.
My quotes:
Couldn't you just special-case BTC similarly: require a working submitpackage only in that case?
for BTC we can require it
I was suggesting we make submitpackage mandatory for electrum protocol 1.6 for bitcoin only. For BTC only. Not for the other altcoins. For those, like I said already, you could declare 1.6 without the new RPC.
Again, for every other altcoin, the server can declare 1.6 regardless of the RPC.
The server knows what coin it is being run for. We have already made coin-specific distinctions in the protocol spec in the past. It is not without precedent, if that matters. You very clearly know this as you have made bcash-specific changes yourself. There are methods that are only available for Namecoin or Dash or other random altcoins.
Your philosophy is refuse to claim support for 1.6 if submitpackages is missing — with no consideration for other coins or networks where the entire facility is absent as a concept
What do you mean "no consideration"? I very clearly was considering other coins in my comments. I was asking you to explain your thinking. I even asked this, to which if you replied positively, I would have considered this whole thread resolved:
Ah. Are you thinking about the scenario, where an altcoin that does not care about broadcast_package now, might introduce it in the future, after 1.6 is widely rolled out? For that case, feature flags might indeed be useful.
but no, instead you called me a statist and started ranting about philosophy.
Yes sure, I am against freedom and that's why I have spent a considerable amount of my life working on Bitcoin. Good catch. Believe whatever you will.
Nodes or even entire coins lacking submitpackages are forever relegated to 1.4 or 1.5 protocol version for all eternity — is what you are proposing.
Please quote the exact sentence where I implied anything of the sort.
I am trying to warn you that this is bad design. It's far better to make use of the features map esp. since the rate of adoption of >= v28 Core/Knots is low. You don't want to antagonize your admins. It's better to warn on startup like I do here: cculianu/Fulcrum@06b50dc#diff-3884123fb22804742dac29791cafa44d2305af37f752aada08460afff7d5c4dcR319-R320
No, it's not better to just warn the operator. It is an alternative reasonable approach, but it is not objectively better. I explained how it is actively harmful to run a public electrum server participating in peer-discovery that is backed by an old bitcoind. Please try to refute my line of thinking there if you disagree on this specific point.
But in short, clients would unknowingly connect to such servers and even in the best case get back error messages when broadcasting a tx: users will then complain on the forums / irc / github, that stuff "does not work" and it will take 2-3 rounds of back-and-forth to figure out what is going on. Don't know about you but I don't fancy doing level1 support much.
And that's assuming the best case, when there is a clear error message that gets triggered on a user-initiated action.
Now imagine automatic logic needing to force-close a lightning channel and getting errors on tx-broadcast - that's not user-initiated action. Not a scenario you want to get hard-to-decipher errors coming from bitcoind and passed on to the server. Or not even getting an error, because the client connected to bitcoin core 26 and submitpackage "works" but does nothing. Sure, the client can have logic to try to deal with all this and ultimately will have to handle even silent failures, but please, let's try to keep the practically occurring common cases working by default with a high probability.
Comparing it to segwit or taproot or v0.0.3 other stuff is not honest argumentation on your part (you are intentionally not arguing in good faith here. Stop being manipulative and be reasonable!).
Was calling me a statist and saying I am on a power trip done in good faith? :)
I listed many policy changes that happened over the years and are scattered throughout time. Some of them are actually very recent, from 28.x and even 29.0 (!!) (e.g. ephemeral dust). I highlighted taproot to give a well known example. Sure, taproot support is widespread now, so you could argue all nodes support it. For context, taproot spending support was added in 0.21, released 2021-01.
Then again, in spesmilo/electrumx#318, you were asking about e-x's reliance on estimatesmartfee and its mode arg, which was added in 0.15, released 2017-09. That's why I cheekily asked if you also want to support bitcoin core 0.3 -- do you really not want to assume a younger than 8 year old bitcoind? So I guess taproot is old enough to be an unreasonable example but estimatesmartfee, well, who knows if bitcoind supports that?
Out of curiosity, what is the minimum version of Bitcoin Core that Fulcrum supports?
Also, do you regularly test with that version when you make changes to daemon RPC calls?
Also note that adding a broadcast_package key to server.features as you suggested has very limited usefulness if only Fulcrum does it. In that case it is only really useful if Fulcrum tries hard to put broadcast_package=false in the map. The "missing" and "true" keys cannot be reliably filtered for if others don't put true values in their map. Maybe you already realised this, I just wanted to highlight this point.
Let me explicitly state what I would have thought was already apparent from my previous comments.
I think it would be reasonable and I am asking if it's acceptable if we
- put a tri-state (false/missing/true) marker into
server.featuresfor submitpackage, regardless of coin (so both for BTC and for others) - for BTC only, we require
submitpackage_marker=truefor protocol version 1.6. That is, we guarantee (on a best-effort basis I guess) that the new RPC is available and works when the new protocol is negotiated. (for BTC only)
Alternatively, we could also make the new submitpackage-based RPC specific to BTC. Just like there are Namecoin/Dash-only RPCs, it would only be exposed if COIN=BTC. No other coin cares about it anyway.
There was a problem hiding this comment.
In theory the backing bitcoind could also be btcd, etc. It would be nice not to "require" Bitcoin Core in the protocol itself. Specific server implementations can require Bitcoin Core or specific versions of Core, that's fine I think, but the protocol ideally should not. Maybe btcd has an equivalent RPC to
submitpackageand a server implementation is then free to use that.The expectation is that if the server claims to support protocol version 1.6, they should have a working
blockchain.transaction.broadcast_package. Hence I see no point in putting stuff intoserver.featuresfor this.
Agree with @SomberNight here. I don't think it makes sense to make this an 'optional' feature.
|
|
||
| 5. Order mempool transactions by ``(-height, tx_hash)``, that is, | ||
| ``0`` height txs come before ``-1`` height txs, and secondarily the | ||
| txid (in network byteorder) is used to arrive at a canonical ordering. |
There was a problem hiding this comment.
Note that the byteorder used for the sorting is not the human-readable txid byteorder but the network one.
I chose this because it fits the existing internals of electrumx much nicer.
However in cculianu/electrum-cash-protocol#5 (comment) @cculianu expressed frustration about this choice.
I guess I don't mind either way though.
Any strong opinions?
There was a problem hiding this comment.
I appreciate your asking others for feedback on this.
the network one.
Just to be annoying -- I'll smartly say that it can be argued the "network" order is only useful if you speak the p2p protocol. Otherwise it can be argued the true network order is the RPC order. :P
There was a problem hiding this comment.
Any strong opinions?
Network byteorder makes sense to me for such an internal behavior, IMO. But, the most important thing is that it's well defined.
There was a problem hiding this comment.
I added a detailed example in 919df4f, to try to avoid any misunderstanding.
There was a problem hiding this comment.
You guys are seriously muddled in your thinking:
- First off, referring to it as "network" order is misleading. WHICH network are we referring to here? The p2p protocol? Nobody involved in Electrum-style wallets speaks that protocol.
- For the purposes of this discussion, let's be more precise:
- Electrum protocol uses "big endian" hash order (that is, reversed from the in-memory order one gets from sha256d) -- it uses this EVERYWHERE in the protocol.
- Bitcoin p2p network, for its messages, etc, uses "little endian" hash order (that is, exactly what you get from sha256d).
This latter thing you are calling "network" order. However the term is misleading because for our network, the network order is actually the other order! The big endian order!
Are we clear on that?
So what you are proposing is that this will be the only place anywhere within this protocol where we are to look at txn hashes as being in the opposite order from every other place.
Are we clear on what is happening here?
I strongly disagree with this approach since:
- It's unexpected
- It's ugly
- There is no justification for it other than "well Electrum does it this way..."
Please change this to what Fulcrum was already doing since 2020.
I won't comply with this in Fulcrum because it's dumb. Sorry. I already solved this problem in 2020 and it's doing the "natural" thing -- using the hash order for the hashes as they appear everywhere else in the protocol. That's what most people expect.
What you want to do here is just unexpected and creates more work for me. And all for no good reason. No can do. Sorry.
There was a problem hiding this comment.
I don't have a strong opinion, but Cormorant (Sparrow's EPS clone) is using big endian order as well. And I agree stating 'big endian' or 'little endian' is clearer.
There was a problem hiding this comment.
First off, referring to it as "network" order is misleading. WHICH network are we referring to here? The p2p protocol? Nobody involved in Electrum-style wallets speaks that protocol.
Fair enough, I meant the bitcoin p2p network.
- For the purposes of this discussion, let's be more precise:
- Electrum protocol uses "big endian" hash order (that is, reversed from the in-memory order one gets from sha256d) -- it uses this EVERYWHERE in the protocol.
- Bitcoin p2p network, for its messages, etc, uses "little endian" hash order (that is, exactly what you get from sha256d).
Is that really more precise? Unlike what you say, the output of sha256 is big-endian. :D
see page 12 (of 36) of https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf :
Throughout this specification, the “big-endian” convention is used
See also, https://en.wikipedia.org/wiki/SHA-256, where at least for the pseudo-code it states:
Big-endian convention is used [...]
Or see e.g. https://learnmeabitcoin.com/technical/general/little-endian/ , which says little-endian is used for integers but big-endian is used for hashes in the bitcoin p2p protocol.
Even if you still disagree, at least please accept that it is not intuitive or clear what big-endian or little-endian is when thinking of the byte-vector output of a hash function. The output is not an integer.
Clearly it is not intuitive if what you thought is actually the opposite of what the standard says.
I won't comply with this in Fulcrum because it's dumb. [...] No can do. Sorry.
Ok, I changed the order to what you suggested.
I wish you had been clearer from the start that this is a complete blocker for you.
See 394a8fd
And I agree stating 'big endian' or 'little endian' is clearer.
I disagree. I hope I illustrated how that would not be clear at all. :P
The updated text now says:
the txid (endianness same as human-readable hex string used for display) is used to arrive at a canonical ordering.
I think that should be clear. And in any case, there is an example.
and creates more work for me.
I just spent an hour updating the server code, the client code, and writing a new example for the spec.
It was writing the new example that took most of that time.
Is it really that much work to add a reverse iterator or a minus sign to your comparator?
The diff was 6 characters in e-x:
spesmilo/electrumx@0f3e261
|
How does everybody here feel about adding a key to the Rational: I am definitely adding this key to Fulcrum. Since unlike ElectrumX, I do plan on continuing to support older or different bitcoind's, etc. So, it's entirely possible some servers out there will not have this RPC, so it's only fitting to advertise whether they have it or not in Here is the proposed text for this as I'm adding it to my documentation now (under the docs for
EDIT: Oh, I see, @SomberNight said he is opposed to claiming 1.6 if this facility is missing. Well, fine. I'm adding the key anyway. I will support "1.6" on Fulcrum with or without |
Not a fan of a feature flag just to add support for a new RPC call.
Please don't advertise support for v1.6 then. In my experience with different implementation |
|
|
||
| 5. Order mempool transactions by ``(-height, tx_hash)``, that is, | ||
| ``0`` height txs come before ``-1`` height txs, and secondarily the | ||
| txid (in network byteorder) is used to arrive at a canonical ordering. |
There was a problem hiding this comment.
Any strong opinions?
Network byteorder makes sense to me for such an internal behavior, IMO. But, the most important thing is that it's well defined.
|
|
||
| .. note:: The exact relay behaviour might depend on the bitcoind version of the server. | ||
|
|
||
| .. note:: Server implementations should verify (e.g. by enforcing a minimum bitcoind version at runtime) |
There was a problem hiding this comment.
In theory the backing bitcoind could also be btcd, etc. It would be nice not to "require" Bitcoin Core in the protocol itself. Specific server implementations can require Bitcoin Core or specific versions of Core, that's fine I think, but the protocol ideally should not. Maybe btcd has an equivalent RPC to
submitpackageand a server implementation is then free to use that.The expectation is that if the server claims to support protocol version 1.6, they should have a working
blockchain.transaction.broadcast_package. Hence I see no point in putting stuff intoserver.featuresfor this.
Agree with @SomberNight here. I don't think it makes sense to make this an 'optional' feature.
| ] | ||
| } | ||
|
|
||
| When *verbose* is :const:`true`:: |
There was a problem hiding this comment.
If we really care that this endpoint could ever be implemented by something else than Bitcoin Core, it might make sense to simplify the return values (esp. the verbose one), as they are very specific to Bitcoin Core. However, the chances are rather slim that we'll see any other implementation supporting package relay/TRUC any time soon.
There was a problem hiding this comment.
The verbose=True response should not be relied upon by clients, its structure entirely depends on bitcoind.
This is similar to the existing blockchain.transaction.get:
electrum-protocol/docs/protocol-methods.rst
Lines 576 to 585 in c366dc6
Clients are expected to use verbose=False, which is guaranteed stable. verbose=True is there for debugging or quick scripts, or potentially hacky stopgaps if bitcoind adds some useful field in the future and the electrum protocol moves slow. (some prior discussion in #1 (comment))
I have clarified this more now in a new commit:
b269a8f
There was a problem hiding this comment.
Clients are expected to use
verbose=False, which is guaranteed stable.verbose=Trueis there for debugging or quick scripts, or potentially hacky stopgaps if bitcoind adds some useful field in the future and the electrum protocol moves slow. (some prior discussion in #1 (comment))
Btw., note that this instability for tranaction_get has been pretty annoying for us in the past, as AFAIU it's the only way to get the status of a transaction in a single call (i.e., get if/in which block hash / height a transaction was confirmed). All other ways to get the same data require sequential calls, which is not only much less efficient, but also error prone to become inconsistent as the chain might change while we're still trying to aggregate all the necessary data.
And independent of whether Core changes any return values, it can't be currently leaned on, as some implementation simply don't handle it (see for example Blockstream/electrs here: https://github.com/Blockstream/electrs/blob/f1823d82b03dbd1dfef53f7b3611128dd2f4c1d2/src/electrum/server.rs#L386 , even though they happily announce support for protocol v1.4). I'm noting this here as it is a prime example why I'm strongly against advertising a protocol version for which you don't support the full feature set.
| Version 1.5 | ||
| =========== | ||
|
|
||
| (this version number was skipped, no corresponding protocol is defined) |
There was a problem hiding this comment.
Note that I skipped 1.5.x as Fulcrum and https://github.com/cculianu/electrum-cash-protocol uses these version numbers.
However I now realise this is nevertheless somewhat problematic:
if a client wants to support protocol version 1.4 and 1.6 but not 1.5.x, they are in quite a pickle.
If the client sends server.version("electrum/4.6.2", ["1.4", "1.6"]) to Fulcrum 2.0, the server will select protocol version 1.5.x.
By design of server.version, clients must support a continuous range of versions.
OTOH, servers are free to pick-and-choose any particular protocol version they want and can skip interim versions.
From a quick read of "electrum-cash-protocol", I think all the changes in the interim versions are backwards compatible. So maybe this is all ~fine... Nevertheless, the situation is unfortunate.
| **Example** | ||
|
|
||
| Redundant unknown arguments MUST be ignored and tolerated by the server:: | ||
|
|
||
| server.version("electrum/4.6.2", ["1.4", "1.6"], "trailing_garbage1", 9999.9, "dd": {}) |
There was a problem hiding this comment.
Sorry for last minute changes. I added this now, another trivial but highly useful and kind of breaking change.
The context is #7.
It looks like electrs already behaves like this, however electrumx and fulcrum send back RPCErrors.
Basically I think we could later add an extra options param, to allow for more fine-grained feature negotiation in some cases. It should probably be used rarely though, I think it would be desirable to avoid fragmentation. Ignoring extra args is a prerequisite for any such change, which should be spec'd out ASAP.
There was a problem hiding this comment.
+1 on this - feature negotiation at the start of the conversation would be a very useful improvement!
| .. note:: If the input is malformed, notably if `raw_txs` is not a well-formed package, | ||
| errors will be sent back as JSON RPC ERROR, as usual. | ||
| Ultimately the distinction can depend on bitcoind. | ||
| Compare examples (id=3 gets JSON RPC ERROR, but id=4 gets success=false with errors array):: |
There was a problem hiding this comment.
After implementing this RPC in electrum (client), I think this note (and examples) should be here for other implementers to see. It is not immediately obvious that errors can come back at two different abstraction layers.
|
Could I ask people to re-ACK? We have an implementation in electrumx: spesmilo/electrumx#317 (+ other already merged PRs linked from there). Ultimately the changes between 1.4.x and 1.6 are very simple. |
|
reACK c617d4d.
+1. For BTC it is reasonable to continue to advertise 1.4.2 as the max supported version if |
I agree. It is reasonable to expect operators to update Bitcoin Core from time to time. |
|
All of you in here saying not to advertise 1.6 when This protocol has a "features" map precisely for the purpose of servers announcing available features. That is, for the non-linearity that arises due to various incompatibilities/warts/etc that exist across coins and across node implementations for any 1 coin. However, due to simplistic linear-thinking bias, you all are making a protocol design mistake. I will release Fulcrum with v1.6 support, maybe I decide to do the stupid thing you recommend in the BTC case, maybe I won't. But I consider your collective sensibilities at protocol design to be .. less than stellar. |
| * Breaking change for the version negotiation: we now mandate that | ||
| the :func:`server.version` message must be the first message sent. | ||
| That is, version negotiation must happen before any other messages. | ||
| * Also for :func:`server.version`, the server must tolerate and ignore |
There was a problem hiding this comment.
This is stupid. Again, this is what the features map is for. But whatever.
|
ACK 394a8fd |
|
Thank you all for the comments and reviews. :) |
This implements the remainder of the protocol 1.6 changes, and it bumps PROTOCOL_MAX to "1.6". Some of protocol 1.6 was merged previously, see e.g.: - #288 - #302 - kyuupichan/electrumx#1001 - #325 ref spesmilo/electrum-protocol#6 ref #317
…CI, replaces #11) (#12) * cli: aggressively log version and "spesmilo" at startup to help distinguish logs from kyuupichan/electrumx ref spesmilo/electrumx#306 * fix: handle correctly the session limiting mechanism This prevents the DoS attack vector caused by hitting the max number of sessions. Prior to this change if the max number of sessions was reached, the server would stop listening for new connections until ALL existing connections were closed. Now, the listening port is closed, the existing connections remain live and when the lower threshold is reached, the listening socket is reopened. * add mempool.get_info, update relayfee comments Adds the `mempool.get_info` rpc to fetch mempoolminfee, minrelaytxfee and incrementalrelayfee from the daemons getmempoolinfo rpc for protocol version 1.6. Updates the relayfee comments as the fee returned by `blockchain.relayfee` doesn't guarantee to get into the mempool as previously stated in the docstrings. * banner: fix daemon version parsing The parsing of the version number returned from 'getnetworkinfo' was not adapted to the changed bitcoin core version number scheme since core went from beta to stable. The banner incorrectly showed 0.29.0 instead of 29.0.0. * daemon: check daemon version on startup Checks the daemon version on startup against a minimum allowed daemon version hardcoded in the corresponding `Coin`. This allows ensure that the connected daemon is running a version that supports all the rpc calls electrumx requires. * v1.6: guard new methods behind 1.6 ptuple Guards the new `blockchain.transaction.broadcast_package` and `mempool.get_info` methods of protocol 1.6 behind this versions ptuple in `set_request_handlers` so they are only exposed in protocol versions >= 1.6. Also stops exposing the `blockchain.relayfee` endpoint for version >= 1.6 as it got removed in 1.6. * mempool.py: add a few type hints * session: broadcast_package: followup #288 Removes the incorrect and unnecessary txid calculation in `ElectrumX.package_broadcast()`, the daemon will complain anyways if the transactions are invalid. * session: estimatefee: normalize mode arg Make mode uppercase if passed as neither the protocol nor core do specify any requirement here. * session.py: sanitize inputs for tx broadcast RPCs * session: fix ReplyAndDisconnect usage for DROP_CLIENT_UNKNOWN was just sending back a response with value 1, instead of a jsonrpc error ref spesmilo/electrumx@860ff53 * session: fix ReplyAndDisconnect. was broken for PaddedRSTransport * add warmup budget to PaddedRSTransport Adds a 1024 (unpadded) byte sending budget to the PaddedRSTransport below which messages are instantly flushed down the socket before the transport will beginn waiting for the buffer to reach MIN_PACKET_SIZE (1024). This allows to get the first couple of messages sent quickly when a wallet connects to improve its ux. * protocol change: server.version must be the first message on the wire related: spesmilo/electrumx#8 * session: wait for protocol ver negotiation to finish before other reqs We already enforce that server.version must be the first received message in a session, but we also need to ensure that the server finishes processing that message and sets up the correct protocol version before starting to process further messages. * docs: update to reflect removal of DROP_CLIENT_UNKNOWN envvar * session: 'server.version' must tolerate and ignore extra unknown args to leave room for future extensions * protocol change: define order of mempool txs in status of scripthash Note that this is a soft fork: the server can apply it even for past protocol versions. Previously, with the order being undefined, if an address had multiple mempool transactions touching it, switching between different servers could result in a change in address status simply as a result of these servers ordering mempool txs differently. This would result in the client re-requesting the whole history of the address. ----- D/i | interface.[electrum.blockstream.info:60002] | <-- ('blockchain.scripthash.subscribe', ['660b44502503064f9d5feee48726287c0973e25bc531b4b8a072f57f143d5cd0']) {} (id: 12) D/i | interface.[electrum.blockstream.info:60002] | --> 9da27f9df91e3f860212f65b736fa20a539ba6e3d509f6370367ee7f10a4d5b0 (id: 12) D/i | interface.[electrum.blockstream.info:60002] | <-- ('blockchain.scripthash.get_history', ['660b44502503064f9d5feee48726287c0973e25bc531b4b8a072f57f143d5cd0']) {} (id: 13) D/i | interface.[electrum.blockstream.info:60002] | --> [ {'fee': 200, 'height': 0, 'tx_hash': '3ee6d6e26291ce360127fe039b816470fce6eeea19b5c9d10829a1e4efc2d0c7'}, {'fee': 239, 'height': 0, 'tx_hash': '9e050f09b676b9b0ee26aa02ccee623fae585a85d6a5e24ecedd6f8d6d2d3b1d'}, {'fee': 178, 'height': 0, 'tx_hash': 'fb80adbf8274190418cb3fb0385d82fe9d47a844d9913684fa5fb3d48094b35a'}, {'fee': 200, 'height': 0, 'tx_hash': '713933c50b7c43f606dad5749ea46e3bc6622657e9b13ace9d639697da266e8b'} ] (id: 13) D/i | interface.[testnet.hsmiths.com:53012] | <-- ('blockchain.scripthash.subscribe', ['660b44502503064f9d5feee48726287c0973e25bc531b4b8a072f57f143d5cd0']) {} (id: 12) D/i | interface.[testnet.hsmiths.com:53012] | --> f7ef7237d2d62a3280acae05616200b96ad9dd85fd0473c29152a4a41e05686c (id: 12) D/i | interface.[testnet.hsmiths.com:53012] | <-- ('blockchain.scripthash.get_history', ['660b44502503064f9d5feee48726287c0973e25bc531b4b8a072f57f143d5cd0']) {} (id: 13) D/i | interface.[testnet.hsmiths.com:53012] | --> [ {'tx_hash': '9e050f09b676b9b0ee26aa02ccee623fae585a85d6a5e24ecedd6f8d6d2d3b1d', 'height': 0, 'fee': 239}, {'tx_hash': 'fb80adbf8274190418cb3fb0385d82fe9d47a844d9913684fa5fb3d48094b35a', 'height': 0, 'fee': 178}, {'tx_hash': '3ee6d6e26291ce360127fe039b816470fce6eeea19b5c9d10829a1e4efc2d0c7', 'height': 0, 'fee': 200}, {'tx_hash': '713933c50b7c43f606dad5749ea46e3bc6622657e9b13ace9d639697da266e8b', 'height': 0, 'fee': 200} ] (id: 13) * [AuxPow] Add Support for individual block headers instead of a combined hex string Array headers: fix type error Array headers: move variable initialization * Array headers: Refactor AuxPoW * Array headers: Refactor AuxPoW truncation * bump PROTOCOL_MAX to 1.6 ref spesmilo/electrum-protocol#6 * try to raise `ulimit -n` open file limit automatically at startup * prepare release 1.19.0 * lib/tx.py: fix wtxid calculation * lib/tx.py: fix vsize calculation * tests: add more test txs for Bitcoin * coins: add additional default server Adds additional default server for peer discovery bootstrap operated by known contributor. * chore(dockerfile): migrate from RocksDB to LevelDB, update to Python 3.14/Trixie * coins: rm veruscoin, fix CI The verushash dependency of this Veruscoin broke the CI. * refactor(dockerfile): remove rapidjson and leveldb extras, drop libsnappy-dev * don't get stuck during shutdown waiting for SessionManager to stop during shutdown, a busy server could get stuck waiting forever on this log line: ``` INFO:SessionManager:waiting for all server's resources to close ``` This happens if a new client connects *just before* we stop listening for new connections during shutdown. As such a client would not yet get put into the sessions dict of active sessions, and hence we would not close that session, and then we would wait forever on `server.wait_closed()`. note: - the `timeout_after(3)` change should be sufficient to fix the bug described - the `_start_main_loop` change is to fix the logged `Task exception was never retrieved` errors see log: ``` 2026-03-18T17:46:31.449692906Z INFO:ElectrumX:[36] SSL xx.xx.xx.xx:48303, 33 total 2026-03-18T17:46:42.532045642Z WARNING:Controller:received SIGTERM signal, initiating shutdown 2026-03-18T17:46:42.532074094Z INFO:Controller:shutting down 2026-03-18T17:46:42.533451153Z INFO:Prefetcher:cancelled; prefetcher stopping 2026-03-18T17:46:42.534319153Z INFO:BlockProcessor:flushing to DB for a clean shutdown... 2026-03-18T17:46:42.804120065Z INFO:ElectrumX:[8] disconnected. Sent 1,969,736 bytes in 12 messages 2026-03-18T17:46:43.081894786Z INFO:ElectrumX:[37] SSL xx.xx.xx.xx:37196, 7 total 2026-03-18T17:46:43.114221817Z INFO:ElectrumX:[38] SSL xx.xx.xx.xx:37826, 8 total 2026-03-18T17:46:43.136865456Z INFO:ElectrumX:[39] SSL xx.xx.xx.xx:65376, 9 total 2026-03-18T17:46:43.190371349Z INFO:ElectrumX:[40] SSL xx.xx.xx.xx:33240, 10 total 2026-03-18T17:46:43.190926440Z INFO:ElectrumX:[41] SSL xx.xx.xx.xx:48276, 11 total 2026-03-18T17:46:43.331333593Z INFO:ElectrumX:[42] SSL xx.xx.xx.xx:48422, 12 total 2026-03-18T17:46:43.385320324Z INFO:ElectrumX:[43] SSL xx.xx.xx.xx:48290, 13 total 2026-03-18T17:46:43.544174665Z INFO:ElectrumX:[44] SSL xx.xx.xx.xx:57090, 7 total 2026-03-18T17:46:43.660732815Z INFO:SessionManager:stop listening on servers, so no new sessions can be created 2026-03-18T17:46:43.660772535Z INFO:SessionManager:closing down server for rpc://127.0.0.1:8000 2026-03-18T17:46:43.660779193Z INFO:SessionManager:closing down server for tcp://all_interfaces:51001 2026-03-18T17:46:43.660784024Z INFO:SessionManager:closing down server for ssl://all_interfaces:51002 2026-03-18T17:46:43.660788621Z INFO:SessionManager:closing 1 active sessions 2026-03-18T17:46:43.703167858Z INFO:ElectrumX:[45] SSL xx.xx.xx.xx:59458, 1 2026-03-18T17:46:43.704859567Z Task exception was never retrieved 2026-03-18T17:46:43.704919163Z future: <Task finished name='Task-1441' coro=<TaskGroup.spawn() done, defined at /usr/local/lib/python3.12/site-packages/aiorpcx/curio.py:205> exception=RuntimeError('task group terminated')> 2026-03-18T17:46:43.704928112Z Traceback (most recent call last): 2026-03-18T17:46:43.704932863Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 211, in spawn 2026-03-18T17:46:43.704938243Z self._add_task(task) 2026-03-18T17:46:43.704942688Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 157, in _add_task 2026-03-18T17:46:43.704948140Z raise RuntimeError('task group terminated') 2026-03-18T17:46:43.704953072Z RuntimeError: task group terminated 2026-03-18T17:46:43.705579195Z INFO:ElectrumX:[46] SSL xx.xx.xx.xx:53554, 2 total 2026-03-18T17:46:43.706381696Z Task exception was never retrieved 2026-03-18T17:46:43.706410424Z future: <Task finished name='Task-1449' coro=<TaskGroup.spawn() done, defined at /usr/local/lib/python3.12/site-packages/aiorpcx/curio.py:205> exception=RuntimeError('task group terminated')> 2026-03-18T17:46:43.706419012Z Traceback (most recent call last): 2026-03-18T17:46:43.706423835Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 211, in spawn 2026-03-18T17:46:43.706429540Z self._add_task(task) 2026-03-18T17:46:43.706434988Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 157, in _add_task 2026-03-18T17:46:43.706440192Z raise RuntimeError('task group terminated') 2026-03-18T17:46:43.706444770Z RuntimeError: task group terminated 2026-03-18T17:46:43.881900608Z INFO:ElectrumX:[47] SSL xx.xx.xx.xx:33056, 3 total 2026-03-18T17:46:43.882805255Z Task exception was never retrieved 2026-03-18T17:46:43.882834359Z future: <Task finished name='Task-1467' coro=<TaskGroup.spawn() done, defined at /usr/local/lib/python3.12/site-packages/aiorpcx/curio.py:205> exception=RuntimeError('task group terminated')> 2026-03-18T17:46:43.882868552Z Traceback (most recent call last): 2026-03-18T17:46:43.882873974Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 211, in spawn 2026-03-18T17:46:43.882879619Z self._add_task(task) 2026-03-18T17:46:43.882884083Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 157, in _add_task 2026-03-18T17:46:43.882889028Z raise RuntimeError('task group terminated') 2026-03-18T17:46:43.882893514Z RuntimeError: task group terminated 2026-03-18T17:46:43.979113844Z INFO:ElectrumX:[48] SSL xx.xx.xx.xx:53972, 4 total 2026-03-18T17:46:43.980168590Z Task exception was never retrieved 2026-03-18T17:46:43.980197406Z future: <Task finished name='Task-1474' coro=<TaskGroup.spawn() done, defined at /usr/local/lib/python3.12/site-packages/aiorpcx/curio.py:205> exception=RuntimeError('task group terminated')> 2026-03-18T17:46:43.980208788Z Traceback (most recent call last): 2026-03-18T17:46:43.980214166Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 211, in spawn 2026-03-18T17:46:43.980219966Z self._add_task(task) 2026-03-18T17:46:43.980224382Z File "/usr/local/lib/python3.12/site-packages/aiorpcx/curio.py", line 157, in _add_task 2026-03-18T17:46:43.980229240Z raise RuntimeError('task group terminated') 2026-03-18T17:46:43.980233970Z RuntimeError: task group terminated 2026-03-18T17:46:44.005542261Z INFO:SessionManager:waiting for all server's resources to close ``` * readthedocs: update base image * ci: move from Cirrus CI to Github Actions Moves the CI from Cirrus to Github Actions. I didn't move the Coveralls stuff as it was unused anyway. I also bumped the python versions to 3.14. * test_api: create new event loop I bumped the CI to use python3.14 which makes the test fail. The reason is the get_event_loop() call doesn't automatically create a new event loop anymore but instead raises if there is none. * DB storage: implement iterator.seek(key) in a way that works consistently between LevelDB and RocksDB. (written to be used for addr history pagination, in history db) * docs: remove coveralls links * ci: re-add comment to build_docs task * session: broadcast_package RPC: fix name of arg: tx_package->raw_txs to follow protocol spec: https://github.com/spesmilo/electrum-protocol/blob/22deba89418c59b5ae5eb5b61cee3e0b33ce3dfb/docs/protocol-methods.rst?plain=1#L561 This is important in case clients are passing the arg by name. * startup logging: log both "max send" and "max recv" sizes * ci: pycodestyle: raise the max line limit it is more annoying than useful * coins: rm WIF_BYTE field * coins: rm XPUB_VERBYTES, XPRV_VERBYTES fields * (trivial) tx.py: add demarcation line - altcoin separator * coins: add explanation how base58 decoder is used * coins: rm HEADER_VALUES, HEADER_UNPACK fields * coins: rm more unused fields * deps: rm 'attrs', use stdlib dataclasses instead * lrucache: sync with electrum client module (add type hints) * coins: refactor BitcoinMixin, so that it is not used by altcoins * coins: refactor class hierarchy to fit actual Bitcoin better * coins: allow Coin.NET to be None, to indicate abstract class follow-up prev * tests: add a block test for Bitcoin mainnet this is a small block, only around 100 KB serialized (233 kwu) * replace unmaintained rocksdb bindings with f321x's fork f321x's new rocksdb bindings are based on NightTsarina/python-rocksdb [0], plus Claude (LLM) adding support to modern Cython, cpython, and RocksDB. I skimmed the source diff up to the "v2.0.0" tag (commit [1]), and I reproduced the "rocksdb-ng==2.0.0" sdist from PyPI. [2] [0]: NightTsarina/python-rocksdb@dad2509 [1]: f321x/python-rocksdb@c1959a8 [2]: `d683f9ac2c02f4a3e8be184bd4559b2c5a2f982272f06545a6ae20e2ffe1ac11 dist/rocksdb_ng-2.0.0.tar.gz` * daemon: check "txindex" is enabled for bitcoind, error if missing * tests: storage: add testcase for exception during write_batch * coins: update TX_COUNT, TX_PER_BLOCK stats for mainnet/testnet3 * coins: fix PEERS for Bitcoin oooooof * peer discovery: allow short chain splits * coins: update PEERS for testnet3 and testnet4 * env: will rm default DB_ENGINE=leveldb default in 2.0 release - user will need to choose explicitly - but backwards compat for now * coins: add mutinynet signet Adds the mutinynet bitcoin signet as additional coin. * pyproject.toml: migrate to newer style "license" declaration ref spesmilo/electrum-ecc@70e4909 * prepare release 1.20.0 * README: be tiny bit less enthusiastic about running master before 2.0 but if you are reading this commit message, maybe you should be running git master and give feedback! :) * history db: change schema, and rm compaction * history db: change schema: prefix entries with b'H' * db: rm upgrade logic with the pending db changes, an upgrade is ~as fast as a resync from genesis * (trivial) make TXNUM_PADDING a global * db: add parameter for TXOUTIDX_LEN * db: change TXOUTIDX_LEN from 4 to 3, to save db storage size In Bitcoin consensus, a txout index is stored as a uint32_t. However, in practice, an output in a tx uses at least 10 bytes (for an OP_TRUE output), so - to exhaust a 2 byte namespace, a tx would need to have a size of at least 2 ** 16 * 10 = 655 KB, - to exhaust a 3 byte namespace, a tx would need to have a size of at least 2 ** 24 * 10 = 167 MB. * (bugfix) db: change tx_num endianness (LE->BE) to match db comparator History.get_txnums and History.backup depend on ordering of tx_nums, so we want the lexicographical order (used by leveldb comparator) to match the numerical order. This is a breaking change in both the utxo db and the history db. (no migration code is provided.) * db: add (block_hash -> block_height) in-memory map For 1 million blocks, in a python dict, I guess this might take around 100 MB of RAM. // - block_hash is 32 bytes, block_height is a varsize int // - dict size seems to increase by 93 bytes for every new item // - however there is considerable additional overhead, I guess amortized over many adds, // for the hashmap. Looks like it takes around ~145 bytes per item overall. * session: implement "blockchain.outpoint.subscribe" RPC squashed with: - "blockchain.outpoint.subscribe" RPC: add optional "spk_hint" argument - "blockchain.outpoint.subscribe" RPC: implement notifications - "blockchain.outpoint.subscribe" RPC: distinguish heights "-1" and "0" Similar to scripthash statuses, the height of an unconfirmed tx is: - `-1` if it has any unconfirmed parents, - `0` otherwise. - session: implement "blockchain.outpoint.get_status" RPC - "blockchain.outpoint.subscribe": use bitcoind 31 gettxspendingprevout * daemon: require "txospenderindex" for bitcoind, error if missing * session: add "blockchain.scriptpubkey.*" RPCs * session: add 'block_hash' field to 'transaction.get_merkle' * implement new "server.ping" semantics for protocol 1.7 * session: add "bc.tx.testmempoolaccept" RPC * session: add "mempool.recent" RPC * introduce txid_rev, txid_hum terms; add type hints all over txid_rev: txid in same endianness as prevouts are serialised in a raw tx txid_hum: txid in endianness used for human-readable display typically (these are reverses of each other) * session: prefix protocol-handler method names with "phandle_" e.g. to make it clear that these are methods that really need to do input sanitization * db: clean-break lack-of-db-upgrade * session: fixes for "server.ping", and use it to send some naive noise * session: use spec-1.7-defined RPC error code for "history too large" * bump version to 2.0b1 * session: bc.tx.get_merkle: don't include "block_hash" in resp postponing this from protocol 1.7 -- the motivation for adding this field was reliant on the "height" arg being optional, which we are also postponing. * session: "server.features": omit "hash_function" for proto 1.7 * calm pycodestyle * session: "bc.outpoint.subscribe" RPC: rename height to funder_height * session: "bc.outpoint.subscribe" RPC: make spk_hint arg mandatory We don't require it but the protocol spec does, and by checking it is at least provided, at least client impls won't accidentally forget to send it. Client impls could still send an empty string as intentional decision if they really want... * db: factor out {pack,unpack}_txoutidx * db: factor out {pack,unpack}_satoshis_val * db: factor out {pack,unpack}_block_height * db: factor out {pack,unpack}_dyn_header_offset * db: move pack/unpack serialization code into new db_util.py * db: unify everything to use big-endian encoding, not mixed Performance-wise, LE was a tiny bit faster though not consistently. Perf goes 3-4% both ways, twice in LE's favour, once in BE's favour. Still, BE is nicer as that's the natural order for leveldb comparators. ``` $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import unpack_be_uint64, unpack_le_uint64; arr = [random.randbytes(8) for _ in range(10**7)]" "[unpack_be_uint64(x) for x in arr]" 1 loop, best of 10: 1.12 sec per loop $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import unpack_be_uint64, unpack_le_uint64; arr = [random.randbytes(8) for _ in range(10**7)]" "[unpack_le_uint64(x) for x in arr]" 1 loop, best of 10: 1.08 sec per loop $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import pack_be_uint64, pack_le_uint64; arr = [int.from_bytes(random.randbytes(8), byteorder='big') for _ in range(10**7)]" "[pack_be_uint64(x) for x in arr]" 1 loop, best of 10: 683 msec per loop $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import pack_be_uint64, pack_le_uint64; arr = [int.from_bytes(random.randbytes(8), byteorder='big') for _ in range(10**7)]" "[pack_le_uint64(x) for x in arr]" 1 loop, best of 10: 705 msec per loop ``` ``` $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import unpack_be_uint32, unpack_le_uint32; arr = [random.randbytes(4) for _ in range(10**7)]" "[unpack_be_uint32(x) for x in arr]" 1 loop, best of 10: 1.03 sec per loop $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import unpack_be_uint32, unpack_le_uint32; arr = [random.randbytes(4) for _ in range(10**7)]" "[unpack_le_uint32(x) for x in arr]" 1 loop, best of 10: 1.03 sec per loop $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import pack_be_uint32, pack_le_uint32; arr = [int.from_bytes(random.randbytes(4), byteorder='big') for _ in range(10**7)]" "[pack_be_uint32(x) for x in arr]" 1 loop, best of 10: 629 msec per loop $ python3 -m timeit -n1 -r10 --setup "import random; from electrumx.lib.util import pack_be_uint32, pack_le_uint32; arr = [int.from_bytes(random.randbytes(4), byteorder='big') for _ in range(10**7)]" "[pack_le_uint32(x) for x in arr]" 1 loop, best of 10: 605 msec per loop ``` * db: fix silent hist_db corruption if we crash during double-reorg It would be good to write a unit test for this... This is an old regression from when the single DB was split into utxo_db and hist_db in 91ca5fc. If there is a crash (kill -9) in db.flush_backup() after flushing the hist_db but before utxo_db, then the hist_db's tx_count (or flush_count in older code) would be left lower than the utxo_db's. Say there is a simple reorg: (1) we are on chain1, but suddenly chain2 becomes longer so our bitcoind switches to it, so e-x has to back up on chain1. (2) we crash in the middle of db.flush_backup() - just after history.backup() (3) when e-x is restarted, the BlockProcessor will just see the same chain1->chain2 reorg again and back up blocks on chain1. history.backup will be a NO-OP, but that's fine. All good. However, what if there is a double-reorg? flip-flop: chain1->chain2->chain1. That is, between (2) and (3), bitcoind switches back to chain1 as it outgrew chain2. In that case the BlockProcessor will NOT trigger a reorg again. It looks at the utxo_db when considering reorgs, so it will just advance blocks forward on chain1. But the hist_db already backed up some blocks in (2)! The address history from those blocks will forever be missing from hist_db: this is a silent db corruption. * env: rm DB_ENGINE default value * rm plyvel from base install, extend release notes * sessions: _notify_inner: rename alias to scripthash * session: mempool_txoutpoint_statuses: store dataclass instead of dict * lib/tx.py: TXOSpendStatus: rename prev_height to funder_height * lib/tx.py: make TXOSpendStatus immutable * session: fix regressed _calc_txoutpoint_status followup 8ba533c ``` ERROR:ElectrumX:[0] taskgroup died. Traceback (most recent call last): File "/home/user/wspace/electrumx/./src/electrumx/server/session.py", line 994, in main_loop async with self.taskgroup as group: ^^^^^^^^^^^^^^ File "/home/user/wspace/electrumx/.venv/lib/python3.13/site-packages/aiorpcx/curio.py", line 304, in __aexit__ await self.join() File "/home/user/wspace/electrumx/./src/electrumx/lib/util.py", line 389, in join task.result() ~~~~~~~~~~~^^ File "/home/user/wspace/electrumx/./src/electrumx/server/session.py", line 1255, in notify await self._notify_inner( ...<3 lines>... ) File "/home/user/wspace/electrumx/./src/electrumx/server/session.py", line 1341, in _notify_inner spend_status_dict = self._convert_txospendstatus_to_protocol_dict(spend_status) File "/home/user/wspace/electrumx/./src/electrumx/server/session.py", line 1496, in _convert_txospendstatus_to_protocol_dict assert spend_status.spender_height is not None ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError ``` * session: run notify in session's taskgroup instead of manager's if notify raises, disconnect session * session: better handle if bitcoind errors in _notify_inner * daemon: mention limitation of check_version and check_indexes * session: rename _spender_for_txo to reflect it ignores mempool events * session: _calc_oc_txo_status: add reorg-paranoia * session: add oc_txo_status_cache Cache the result of _calc_oc_txo_status (the non-mempool txo status), as that calculation involves two bitcoind RPC calls, and bitcoind RPCs are ~expensive. Also note _notify_inner calls _calc_oc_txo_status twice, for any given prevout. * local rpc: reorganise cache statistics in getinfo * local rpc: also show cache stats for estimatefee * session: add comment re txs_sent "double-counting" * local rpc: show cache hit rate (ratio) stat * local rpc: new command: "inspect_session" example: ``` $ ./electrumx_rpc inspect_session 4 { "client_name": "electrum/4.7.2", "conn_time": "38s", "errors": 0, "is_logged": false, "pending requests": 0, "request counts": { "blockchain.estimatefee": 6, "blockchain.headers.subscribe": 1, "blockchain.scripthash.subscribe": 66, "mempool.get_fee_histogram": 1, "mempool.get_info": 1, "server.banner": 1, "server.donation_address": 1, "server.features": 1, "server.peers.subscribe": 1, "server.ping": 1, "server.version": 1 }, "request total": 81, "subs_sh": 66, "subs_txo": 0, "txs sent": 0 } ``` * session: store longer client_name * mempool: trigger refresh after db_height changes, don't wait for poll I want to minimise the time when the following does not hold: daemon.cached_height() == block_processor.height == db.db_height == session_mgr.notified_height * session: add "chaintip" field to protocol 1.7 responses * session: add comment re get_history race * session: add more logging to retry_on_chain_sync_error * prefetcher: trigger refresh after daemon height changes, don't wait for poll similar to 34d7111 I want to minimise the time when the following does not hold: daemon.cached_height() == block_processor.height == db.db_height == session_mgr.notified_height * bp,db,hist: add type hints * session: retry_on_chain_sync_error: allow daemon_height to differ Also, comparing heights was not enough: a reorg from height h to height h can happen if it crosses a difficulty retarget boundary. * db: BlockProcessor should not update db.bhash_to_bheight directly propagate updates through flush_data, to have better consistency guarantees when BlockProcessor.tip == DB.tip * session: wrap more protocol handlers with retry_on_chain_sync_error follow-up spesmilo/electrumx#362 * session: retry_on_chain_sync_error: log time taken, add comments * hist db: clear_excess: log progress * init: log whether GIL is enabled * json: replace unmaintained ujson/rapidjson extras with orjson ujson and rapidjson were both rather unmaintained and potentially even slower than modern python stdlib json. Replace them with the maintained and performant orjson library instead. * bp: add a few asserts, small comments for upcoming refactor for perf * bp: advance_txs: two loops for tx processing: (1) outputs, (2) inputs We don't care about the order of the txs in the blocks: bitcoind should have already validated consensus rules, we just trust bitcoind. Having two loops will allow parallelising processing the txs. * bp: advance_txs: pre-allocate undo_info * bp: advance_txs: use threadpool for processing tx-inputs spend_utxo() does disk reads, so previously any single disk read would block the whole of advance_txs(). * bp: check_and_advance_blocks: use threadpool for block-parsing * bp: advance_txs: make process-tx-outputs less sequential re tx_num * bp: advance_txs: use threadpool for processing tx-outputs processing tx-outputs is fully CPU-bottlenecked, so this will only be faster if running python without the GIL * bp: advance_txs: split into two functions: inputs and outputs * bp: change undo_infos to dict towards parallelising advance_blocks * bp: advance_blocks: separate loops for txouts and txins * bp: advance_blocks: use threadpool to proc multiple blocks concurrently * bp: two code paths, based on gil_enabled :( splitting the workload across threads makes things significantly slower if there is a GIL * hist db: change "unflushed" to simple set this will be friendlier for multi-threaded writes into it, than appending to bytearrays * bp: advance_blocks: parallelise history.add_unflushed() calls * bp: add comments re methods being thread-safe * bp: LTORBlockProcessor: rm advance_txs * bp: maybe fix NameIndexBlockProcessor blindly adapt to recent changes of advance_txs * changelog: add section about performance improvements * update docs/PERFORMANCE-NOTES: rm stale mentions of json parsers follow-up fcdc956 * altcoin: verge: add peers (#365) * util: rm custom cachedproperty, became part of stdlib in py 3.8 * rm some old bsv propaganda :) * env: COIN no longer mandatory, defaults to "Bitcoin", again default was previously removed in spesmilo/electrumx@3cc5b5e, around bcash fork * controller/bp: add more shutdown logging had an exception that did not get logged anywhere... --- before: ``` DEBUG:Daemon:new height: 8887 DEBUG:MemPool:waiting for DB to sync INFO:Prefetcher:new block height 8,887 hash 6496d4c0774e2d804167c491d97855ce7988d459994e288628bae1b4aac3cb94 DEBUG:BlockProcessor:new height: 8887 INFO:DB:flush took 0.0s. Height 8,887 txs: 9,519 (+1) INFO:Prefetcher:cancelled; prefetcher stopping INFO:SessionManager:stop listening on servers, so no new sessions can be created INFO:SessionManager:closing down server for rpc://127.0.0.1:8000 INFO:SessionManager:closing down server for tcp://127.0.0.1:51001 INFO:SessionManager:closing down server for ssl://127.0.0.1:51002 INFO:SessionManager:closing down server for tcp://[::1]:51001 INFO:SessionManager:closing down server for ssl://[::1]:51002 INFO:SessionManager:closing 0 active sessions INFO:SessionManager:waiting for all server's resources to close <hang> ``` after: ``` DEBUG:Daemon:new height: 8886 INFO:Prefetcher:new block height 8,886 hash 4662fcd5308e94cbbe82754d94a59123942c4009d62e88a653d5dabca48423dd DEBUG:BlockProcessor:new height: 8886 INFO:DB:flush took 0.0s. Height 8,886 txs: 9,518 (+1) ERROR:BlockProcessor:_process_prefetched_blocks got exception: Non-thread-safe operation invoked on an event loop other than the current one INFO:BlockProcessor:_process_prefetched_blocks exiting INFO:Prefetcher:cancelled; prefetcher stopping ERROR:BlockProcessor:fetch_and_process_blocks taskgroup died. Traceback (most recent call last): File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 884, in fetch_and_process_blocks async with OldTaskGroup() as group: ~~~~~~~~~~~~^^ File "/home/user/wspace/aiorpcX/aiorpcx/curio.py", line 304, in __aexit__ await self.join() File "/home/user/wspace/electrumx/./src/electrumx/lib/util.py", line 375, in join task.result() ~~~~~~~~~~~^^ File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 833, in _process_prefetched_blocks await self.check_and_advance_blocks(blocks) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 264, in check_and_advance_blocks await self._maybe_flush() File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 415, in _maybe_flush await self.flush(True) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 409, in flush await self.run_in_thread_with_lock(flush) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 242, in run_in_thread_with_lock return await asyncio.shield(run_in_thread_locked()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 241, in run_in_thread_locked return await run_in_thread(func, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/wspace/aiorpcX/aiorpcx/curio.py", line 57, in run_in_thread return await get_event_loop().run_in_executor(None, func, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/concurrent/futures/thread.py", line 86, in run result = ctx.run(self.task) File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/concurrent/futures/thread.py", line 73, in run return fn(*args, **kwargs) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 404, in flush self.db.flush_dbs( ~~~~~~~~~~~~~~~~~^ flush_data=self.flush_data(), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ flush_utxos=flush_utxos, ^^^^^^^^^^^^^^^^^^^^^^^^ estimate_txs_remaining=self.estimate_txs_remaining, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "/home/user/wspace/electrumx/./src/electrumx/server/db.py", line 319, in flush_dbs self.db_flushed_event.set() # ~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/asyncio/locks.py", line 192, in set fut.set_result(True) ~~~~~~~~~~~~~~^^^^^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/asyncio/base_events.py", line 829, in call_soon self._check_thread() ~~~~~~~~~~~~~~~~~~^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/asyncio/base_events.py", line 866, in _check_thread raise RuntimeError( "Non-thread-safe operation invoked on an event loop other " "than the current one") RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one INFO:BlockProcessor:fetch_and_process_blocks taskgroup stopped. INFO:SessionManager:stop listening on servers, so no new sessions can be created INFO:SessionManager:closing down server for rpc://127.0.0.1:8000 INFO:SessionManager:closing down server for tcp://127.0.0.1:51001 INFO:SessionManager:closing down server for ssl://127.0.0.1:51002 INFO:SessionManager:closing down server for tcp://[::1]:51001 INFO:SessionManager:closing down server for ssl://[::1]:51002 INFO:SessionManager:closing 0 active sessions INFO:SessionManager:waiting for all server's resources to close INFO:SessionManager:all servers closed <hang> ``` * db: db_flushed_event: fix thread-safety for asyncio.Event() regression from spesmilo/electrumx@34d7111 Was visible when running with: export PYTHONASYNCIODEBUG=1 export PYTHONDEVMODE=1 ``` DEBUG:Daemon:new height: 8886 INFO:Prefetcher:new block height 8,886 hash 4662fcd5308e94cbbe82754d94a59123942c4009d62e88a653d5dabca48423dd DEBUG:BlockProcessor:new height: 8886 INFO:DB:flush took 0.0s. Height 8,886 txs: 9,518 (+1) ERROR:BlockProcessor:_process_prefetched_blocks got exception: Non-thread-safe operation invoked on an event loop other than the current one INFO:BlockProcessor:_process_prefetched_blocks exiting INFO:Prefetcher:cancelled; prefetcher stopping ERROR:BlockProcessor:fetch_and_process_blocks taskgroup died. Traceback (most recent call last): File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 884, in fetch_and_process_blocks async with OldTaskGroup() as group: ~~~~~~~~~~~~^^ File "/home/user/wspace/aiorpcX/aiorpcx/curio.py", line 304, in __aexit__ await self.join() File "/home/user/wspace/electrumx/./src/electrumx/lib/util.py", line 375, in join task.result() ~~~~~~~~~~~^^ File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 833, in _process_prefetched_blocks await self.check_and_advance_blocks(blocks) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 264, in check_and_advance_blocks await self._maybe_flush() File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 415, in _maybe_flush await self.flush(True) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 409, in flush await self.run_in_thread_with_lock(flush) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 242, in run_in_thread_with_lock return await asyncio.shield(run_in_thread_locked()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 241, in run_in_thread_locked return await run_in_thread(func, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/user/wspace/aiorpcX/aiorpcx/curio.py", line 57, in run_in_thread return await get_event_loop().run_in_executor(None, func, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/concurrent/futures/thread.py", line 86, in run result = ctx.run(self.task) File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/concurrent/futures/thread.py", line 73, in run return fn(*args, **kwargs) File "/home/user/wspace/electrumx/./src/electrumx/server/block_processor.py", line 404, in flush self.db.flush_dbs( ~~~~~~~~~~~~~~~~~^ flush_data=self.flush_data(), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ flush_utxos=flush_utxos, ^^^^^^^^^^^^^^^^^^^^^^^^ estimate_txs_remaining=self.estimate_txs_remaining, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) ^ File "/home/user/wspace/electrumx/./src/electrumx/server/db.py", line 319, in flush_dbs self.db_flushed_event.set() # ~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/asyncio/locks.py", line 192, in set fut.set_result(True) ~~~~~~~~~~~~~~^^^^^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/asyncio/base_events.py", line 829, in call_soon self._check_thread() ~~~~~~~~~~~~~~~~~~^^ File "/opt/cpython-versions/3.14.6_nogil/lib/python3.14t/asyncio/base_events.py", line 866, in _check_thread raise RuntimeError( "Non-thread-safe operation invoked on an event loop other " "than the current one") RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one INFO:BlockProcessor:fetch_and_process_blocks taskgroup stopped. INFO:SessionManager:stop listening on servers, so no new sessions can be created INFO:SessionManager:closing down server for rpc://127.0.0.1:8000 INFO:SessionManager:closing down server for tcp://127.0.0.1:51001 INFO:SessionManager:closing down server for ssl://127.0.0.1:51002 INFO:SessionManager:closing down server for tcp://[::1]:51001 INFO:SessionManager:closing down server for ssl://[::1]:51002 INFO:SessionManager:closing 0 active sessions INFO:SessionManager:waiting for all server's resources to close INFO:SessionManager:all servers closed <hang> ``` * mempool: comment how process_mempool works * mempool: topologically sort candidate txs for accept_transactions This reduces worst-case time complexity. The average case looks practically unchanged. * mempool: simplify logic: rm "accept" part of fetch_and_accept only call accept_transactions from a single place * mempool: type-hints: name utxo_map * type-hints: name TxOutpoint * mempool: run accept_txs while-loop on separate thread don't bog down event loop * mempool: more comments for process_mempool * db: during init, move long event-loop-blocking calls to other thread * db: open_dbs: move long event-loop-blocking calls to other thread * storage: rocksdb: use close method from rocksdb-ng * tests: fix confusing comment * mempool: put more event-loop-blocking calls to other thread hex_str_to_hash for 100k txs (~45 MB mempool) takes 0.20 sec handle_disappeared_txs for 5k txs (1 block's worth) takes 0.08 sec new_hashes calc (the set diff) for 100k txs takes 0.03 sec * tests: mempool: fix test_keep_synchronized: was racy/timing-dependent * fix DeprecationWarning: ssl.PROTOCOL_TLS ``` INFO:SessionManager:TCP server listening on 127.0.0.1:51001 /home/user/wspace/electrumx/./src/electrumx/server/session.py:310: DeprecationWarning: ssl.PROTOCOL_TLS is deprecated self._sslc = ssl.SSLContext(ssl.PROTOCOL_TLS) INFO:SessionManager:SSL server listening on 127.0.0.1:51002 ``` * mempool: call getrawmempool as soon as daemon's height changes - bitcoind to serve getrawmempool RPC concurrently to our BlockProcessor processing the new block - with free-threaded python, this shaves off around 0.4 sec of the time until SessionManager.notified_height gets bumped * storage: add some type hints * dedupe min python version * calm pycodestyle * db: clear_excess_undo_info: add logging and comment * db: incrementally clear excess undo infos as we go * tests: storage: add testcase for batch.delete * mempool: refresh_hashes: log time taken * util: add LogTimeTaken context manager, for benchmarking * mempool: log time taken for _update_histogram * mempool: partially revert threading _process_mempool reverts parts of e1ccd4b ead66dd self.txs and self.hashXs and self.txo_to_spender are accessed from the external interface, on the asyncio thread, and they are assumed to be consistent with each other. * session: ChainSyncError: fix some stale comments * session: protocol 1.7: revert including "chaintip" in responses follows spesmilo/electrum-protocol#17 * session: bump PROTOCOL_MAX to 1.7 * contrib/Dockerfile: switch to rocksdb also, - don't pin python patch version - use default env var values - "docker stop" seems cleaner, more intuitive, than kill * contrib: add another Dockerfile, showing use w/ free-threaded python * prepare release 2.0.0 * coins: port the Doichain classes to ElectrumX 2.0 Our fleet runs ElectrumX 1.15.0 (2020). Upstream 2.0.0 moved the tree to src/, merged the name and AuxPoW mixins into NameIndexAuxPoWMixin (which carries SESSIONCLS), turned P2SH_VERBYTES and NAME_OPERATIONS into tuples, added NAME_EXPIRATION, and dropped XPUB/XPRV/WIF entirely -- they have no remaining use anywhere in the tree. Values come from the chain and the consensus rules rather than being carried over unchanged: RPC_PORT 8339 / 18339 8338 is the P2P port since Core 31, so the old value pointed ElectrumX at the wrong socket TX_COUNT 2,742,220 getchaintxstats at height 431,763 NAME_EXPIRATION 36,000 / 30 Consensus::MainNetConsensus::NameExpirationDepth (36,000 above height 48,000; regtest 30) Testnet and regtest inherit from Doichain now instead of repeating every declaration, matching how upstream keeps the Namecoin classes. Verified with the package installed: ElectrumX resolves all three classes, with SESSIONCLS NameIndexAuxPoWElectrumX, DESERIALIZER DeserializerAuxPowSegWit, BLOCK_PROCESSOR NameIndexBlockProcessor, four name operations including name_doi, and REQUIRED_DAEMON_INDEXES empty -- so no extra daemon index is required. tests/lib/test_coins.py: 16 passed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * tests: add Doichain block fixtures CI failed on tests/test_blocks.py::test_all_coins_are_covered: upstream requires every mainnet coin class to come with at least one block fixture, and Doichain had none. 1.15.0 had no such test, so the gap only appears with 2.0. Two blocks, taken from a synced node: - **431,320** -- two transactions, the second a `name_doi`. This is the block the name index was verified against, so the fixture now covers the operation that distinguishes Doichain from Namecoin, through DeserializerAuxPowSegWit. - **100,000** -- an ordinary single-coinbase block, for the plain path. test_block checks the header hash, the previous hash and every txid against the deserialised block; both pass. The remaining failures in that file are `ModuleNotFoundError: No module named 'blake256'` on unrelated coins, which occur with or without these files. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: ghost43 <somber.night@protonmail.com> Co-authored-by: Alex Lupov <alex.lupov.20610521@proton.me> Co-authored-by: f321x <f@f321x.com> Co-authored-by: Ahmed Bodiwala <ahmed_bodi@msn.com> Co-authored-by: Jeremy Rand <jeremyrand@airmail.cc> Co-authored-by: Felix <51097237+f321x@users.noreply.github.com> Co-authored-by: ethicnology <ethicnology@pm.me> Co-authored-by: sunerok <8443713+justinvforvendetta@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

This defines a new protocol version: 1.6, even more minimal than what was previously in #2, just to get something out quickly.
Compared to the existing protocol version 1.4.3:
blockchain.transaction.broadcast_packageto expose bitcoind'ssubmitpackagemempool.get_info, to expose a subset of bitcoin core'sgetmempoolinfoblockchain.relayfeeredundant, which is now removedthe
server.versionmessage must be the first message sent.That is, version negotiation must happen before any other messages.
server.version, the server must tolerate and ignoreextraneous arguments, to allow for extensions in future protocol versions.
backwards-compatible way: mempool txs now have a canonical ordering
defined for the calculation (previously their order was undefined).
blockchain.scripthash.get_mempoolpreviously did not definean order for mempool transactions. We now mandate a specific ordering.
modeargument added toblockchain.estimatefeeblockchain.block.headersnow returns headers as a list,instead of a single concatenated hex string.
The changes here are trivial to implement and hence I believe we can release this quickly.
The rest of #2 (such as outpoint subscriptions and witness-spv) is postponed for protocol version 1.7, which I also intend to have "soon", but the changes in the current PR (notably submitpackage) is even more urgent.
After that, there are still plans even for 2.0, e.g. the history pagination... :)