Post
Topic
Board Development & Technical Discussion
Merits 6 from 3 users
Re: C# Bitcoin Address Validation [Legacy, Nested SegWit, Native SegWit] | OFFLINE
by
BlackHatCoiner
on 20/08/2021, 13:49:38 UTC
⭐ Merited by Coding Enthusiast (2) ,Pmalek (2) ,vapourminer (2)
Even if your issue is resolved, I'll try to clear out some things to you that you possibly don't know. Giving you a bunch of coding lines will only assist you temporarily.

I need a method that returns TRUE or FALSE.
Alright, maybe you aren't familiar that much with coding yet and Coding Enthusiast's scripts may be an overstatement to understand.

First off, it is required for you to know what's the background of a Bitcoin address, how it is structured etc. In this case, I'll explain you how a legacy address' structure, but it works similarly for Native SegWit and Nested SegWit. This bitcoin wiki article is useful. Briefly, a Bitcoin address is a base58 encoding of a string that contains these stuff in the following order: [version prefix][160-bit hash][checksum]

The checksum is the first four bytes of the prefix + 160-bit hash that is hashed two times with SHA256. For instance, if someone gave you this 160-bit hash:

Code:
e01f8922bb5bbfac8d02e77b023f2561fd2fa26b

You could get the checksum as following:

Code:
SHA256("00e01f8922bb5bbfac8d02e77b023f2561fd2fa26b") = 5088bf915b5880a5423a4064266ff534b28d74d4e1dce6e68f3fbf35e4481e32
SHA256("5088bf915b5880a5423a4064266ff534b28d74d4e1dce6e68f3fbf35e4481e32") = 351ca7c467a8c5f19dfb8472f5d4c1f8ee1ed38e2e9254ed1b0f04fec79a19d4
Checksum = 351ca7c4

So, to be able to detect an address, you have to decode it and check if it has the above requirements; if the prefix along with the next 40 characters give you the same 4 bytes once hashed twice with SHA256, with the last 4 bytes of the decoded address. You can google for a base58 decoder script in C#, but it shouldn't be hard to write it yourself if you firstly understand how it works.

In Bitcoin, you should never hash a message as a text, but rather as a byte array.