function test_address($address)
{
    global $addressversion, $base58, $self, $hex, $link, $pattern, $period;
    global $rpcQuery;
    // check it's a valid address
    if ($address == $self) {
        return -1;
    }
    if (!preg_match('/' . $pattern . '/', $address)) {
        return -2;
    }
    $addrhex = base2base($address, $base58, $hex);
    if (strlen($addrhex) !== 50) {
        return -3;
    }
    if (substr($addrhex, 0, 2) !== $addressversion) {
        return -4;
    }
    $check = substr($addrhex, 0, 42);
    $check = pack('H*', $check);
    $check = strtoupper(hash('sha256', hash('sha256', $check, true)));
    $check = substr($check, 0, 8);
    if ($check !== substr($addrhex, 42)) {
        return -5;
    }
    $result = $rpcQuery->validateaddress($address);
    if (!$result['isvalid']) {
        return -6;
    }
    if ($result['ismine']) {
        return -1;
    }
    // returns 0 for success, negative for error
    return 0;
}
function test_address($address)
{
    global $addressversion, $base58, $donations, $hex, $link, $pattern, $period;
    // check it's a valid address
    if ($address == $donations) {
        return -1;
    }
    if (!preg_match('/' . $pattern . '/', $address)) {
        return -2;
    }
    $addrhex = base2base($address, $base58, $hex);
    if (strlen($addrhex) !== 50) {
        return -3;
    }
    if (substr($addrhex, 0, 2) !== $addressversion) {
        return -4;
    }
    $check = substr($addrhex, 0, 42);
    $check = pack('H*', $check);
    $check = strtoupper(hash('sha256', hash('sha256', $check, true)));
    $check = substr($check, 0, 8);
    if ($check !== substr($addrhex, 42)) {
        return -5;
    }
    $params = array(0 => $address);
    $result = send_json_request('validateaddress', $params);
    if (!$result['result']['isvalid']) {
        return -6;
    }
    if ($result['result']['ismine']) {
        return -1;
    }
    // address is ok if we got this far
    // check the database to see if we have already sent coins
    $curtime = time();
    $time = time() - $period;
    if ($stmt = mysqli_prepare($link, 'SELECT time FROM transactions WHERE time > ? AND address = ? ORDER BY time DESC LIMIT ?;')) {
        $limit = 1;
        mysqli_stmt_bind_param($stmt, 'isi', $time, $address, $limit);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $lastreq);
        mysqli_stmt_fetch($stmt);
        mysqli_stmt_close($stmt);
        if ($lastreq > 1) {
            return $period - ($curtime - $lastreq);
        }
    }
    if (mysqli_errno($link)) {
        return -7;
    }
    // returns 0 for success, negative for error, postive for waiting time
    return 0;
}