Skip to content

Commit 2b3e708

Browse files
committed
Fix bug in encoding and decoding bech32
1 parent a8c70ed commit 2b3e708

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

csharp/IotaWalletNet/IotaWalletNet.Domain/Common/Extensions/StringExtensions.cs

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,20 +59,50 @@ public static string EncodeEd25519HashIntoBech32(this string blake2bHashOfEd2551
5959

6060
string bech32 = Bech32Engine.Encode(hrp, Convert.FromHexString(blake2bHashOfEd25519));
6161

62-
const string HRP_CONSTANT = "1";
62+
return bech32;
63+
}
64+
65+
public static string EncodeAliasIdIntoBech32(this string aliasID, NetworkType networkType, TypeOfCoin typeOfCoin)
66+
{
67+
aliasID = aliasID.Trim().ToLower();
68+
if (aliasID.StartsWith("0x"))
69+
aliasID = aliasID.Substring(2); // remove the 0x of a hexstring eg 0x1337
70+
71+
string hrp = HumanReadablePart.GetHumanReadablePart(networkType, typeOfCoin);
72+
const string ALIAS_TYPE = "08";
73+
aliasID = ALIAS_TYPE + aliasID;
74+
75+
string bech32 = Bech32Engine.Encode(hrp, Convert.FromHexString(aliasID));
76+
77+
return bech32;
78+
}
79+
80+
public static string EncodeNftIdIntoBech32(this string nftId, NetworkType networkType, TypeOfCoin typeOfCoin)
81+
{
82+
nftId = nftId.Trim().ToLower();
83+
if (nftId.StartsWith("0x"))
84+
nftId = nftId.Substring(2); // remove the 0x of a hexstring eg 0x1337
85+
86+
string hrp = HumanReadablePart.GetHumanReadablePart(networkType, typeOfCoin);
87+
const string NFT_TYPE = "10";
88+
nftId = NFT_TYPE + nftId;
89+
90+
string bech32 = Bech32Engine.Encode(hrp, Convert.FromHexString(nftId));
6391

64-
return $"{hrp}{HRP_CONSTANT}{bech32}";
92+
return bech32;
6593
}
6694

67-
public static string DecodeBech32IntoEd25519Hash(this string bech32, NetworkType networkType, TypeOfCoin typeOfCoin)
95+
public static string DecodeBech32(this string bech32, NetworkType networkType, TypeOfCoin typeOfCoin)
6896
{
6997
bech32 = bech32.Trim().ToLower();
7098

7199
string hrp = HumanReadablePart.GetHumanReadablePart(networkType, typeOfCoin);
72100

73-
string bech32OfInterest = bech32.Substring(4); //eg remove iota1 or smr1 or atoi1 or rms1
74101

75-
byte[] decoded = Bech32Engine.Decode(bech32OfInterest, hrp);
102+
byte[] decoded = Bech32Engine.Decode(bech32, hrp+"1");
103+
104+
//Remove type bytes
105+
decoded = decoded.Skip(1).ToArray();
76106

77107
return "0x" + Convert.ToHexString(decoded);
78108
}

0 commit comments

Comments
 (0)