TheFox / hashcash

Pure PHP implementation of Hashcash 1.
https://fox21.at
MIT License
19 stars 4 forks source link

implement in webservice #5

Open ghost opened 4 years ago

ghost commented 4 years ago

Hello, beautiful work you did! But I have doubts, how can I implement this in a web service, API RESTFUL, without user login authentication. Just to control the amount of access for a given crawler? Thank you.

TheFox commented 4 years ago

Thank you.

You mean only verifying? So the a client generates a Stamp and on the API site it will be verified.

For example, the client generates a Stamp:

// Client
$hashcash = new Hashcash();
$hashcash->setDate(date(Hashcash::DATE_FORMAT12)); // Using full date.
$hashcash->setBits(20);
$stamp = $hashcash->mint();

And on the API site you verify this Stamp using:

// Server
$hashcash = new Hashcash();
$hashcash->setExpiration(30);
$isOk = $hashcash->verify($stamp) && $hashcash->getBits() >= 20;
printf("OK? %s\n", $isOk ? 'Y' : 'N');
ghost commented 4 years ago

@TheFox Understood. But if you have a lot of people accessing the site, and the an API is checking multiples Stamp above 20 bits per example, won't the server API be slowed?

Ps. My idea is this: I check the amount of access, if a given access gets a rate considered high in a short period of time, my API generates a stamp for the client, in the next request from the client I need to block his access by a certain period of time, so I need a high stamp, above 20bits.

TheFox commented 4 years ago

I understand your concerns but, no. This will not slow down the server because this is the main feature Hashcash provides. The verification functions is very fast. (See Hashcash::checkBitsFast).

Only generating a Stamp (on the client side) will take longer if you use more bits. So you have to choose the proper amount of bits for the client. If you choose too less it doesn't make sense to Hashcash at all, but it should also not too much. It depends on the power of the client CPU. And also on how many API calls one client is doing.

And also on the server side you have to keep a database of all used Stamps. And keep them at least 30 days, so no client can reuse the same Stamp again. Each client has to generate its own Stamps for every time one client want to call an API endpoint.

ghost commented 4 years ago

Understood! I will implement this with and save the stamp in MYSQL. Any questions I will contact you again. Since already, very thankful!

Ps. @TheFox One more thing, is there a need to use the SALT parameter in the stamp? Remembering that the API Scenario does not have Login authentication.