33/**
44 * Unicity network identifier ({@code α}). Used to scope token ids and other
55 * network-bound values so they cannot be replayed across networks.
6- *
7- * <p>{@code 0} is reserved as an uninitialized sentinel and is rejected by
8- * {@link #fromId(short)}.
96 */
10- public enum NetworkId {
11- MAINNET ((short ) 1 ),
12- TESTNET ((short ) 2 ),
13- LOCAL ((short ) 3 );
7+ public final class NetworkId {
8+
9+ public static final NetworkId MAINNET = new NetworkId ((short ) 1 , "MAINNET" );
10+ public static final NetworkId TESTNET = new NetworkId ((short ) 2 , "TESTNET" );
11+ public static final NetworkId LOCAL = new NetworkId ((short ) 3 , "LOCAL" );
1412
1513 private final short id ;
14+ private final String name ;
1615
17- NetworkId (short id ) {
16+ private NetworkId (short id , String name ) {
1817 this .id = id ;
18+ this .name = name ;
19+ }
20+
21+ private NetworkId (short id ) {
22+ this (id , null );
23+ }
24+
25+ /**
26+ * Resolve a NetworkId from its numeric identifier. Returns the registered
27+ * singleton for known ids; constructs a new (unnamed) instance for any
28+ * other 16-bit value.
29+ *
30+ * @param id numeric network identifier
31+ * @return NetworkId for the given identifier
32+ */
33+ public static NetworkId fromId (short id ) {
34+ if (id == MAINNET .id ) {
35+ return MAINNET ;
36+ }
37+ if (id == TESTNET .id ) {
38+ return TESTNET ;
39+ }
40+ if (id == LOCAL .id ) {
41+ return LOCAL ;
42+ }
43+ return new NetworkId (id );
1944 }
2045
2146 /**
@@ -27,19 +52,24 @@ public short getId() {
2752 return this .id ;
2853 }
2954
30- /**
31- * Look up a NetworkId by its numeric identifier.
32- *
33- * @param id numeric network identifier
34- * @return matching network identifier
35- * @throws IllegalArgumentException if {@code id} is not a registered network
36- */
37- public static NetworkId fromId (short id ) {
38- for (NetworkId network : NetworkId .values ()) {
39- if (network .id == id ) {
40- return network ;
41- }
55+ @ Override
56+ public boolean equals (Object o ) {
57+ if (this == o ) {
58+ return true ;
4259 }
43- throw new IllegalArgumentException ("Unknown network identifier: " + id );
60+ if (!(o instanceof NetworkId )) {
61+ return false ;
62+ }
63+ return this .id == ((NetworkId ) o ).id ;
64+ }
65+
66+ @ Override
67+ public int hashCode () {
68+ return Short .hashCode (this .id );
69+ }
70+
71+ @ Override
72+ public String toString () {
73+ return "NetworkId[" + (this .name != null ? this .name : this .id ) + "]" ;
4474 }
45- }
75+ }
0 commit comments